简体   繁体   中英

LoopJ Android Asynchronous Http Client - java.net.SocketTimeoutException

i used library from http://loopj.com/ for async post request, but i get socketTimeOutException, i tried by setting client.setTimeOut(50000); still getting same error.

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams("type", "myType");
    client.post("service.php", params, new AsyncHttpResponseHandler() {

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            System.out.println("Failure");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            System.out.println("Success");
        }

    });
}

}

i tried the same url by httpclient and it works:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://www.example.com/service.php");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("type", "myType"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

I discovered that the AsyncHttpClient actually defaults to a 10 second timeout. If your request takes longer you'll see the SocketTimeoutException thrown.

Adjusting this is really simple. Just do the following:

final int DEFAULT_TIMEOUT = 20 * 1000;
AsyncHttpClient aClient = new AsyncHttpClient();
aClient.setTimeout(DEFAULT_TIMEOUT);
//... continue as normal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM