gpt4 book ai didi

java - LoopJ Android 异步 Http 客户端 - java.net.SocketTimeoutException

转载 作者:行者123 更新时间:2023-12-04 18:05:18 27 4
gpt4 key购买 nike

我使用了来自 http://loopj.com/ 的库对于异步发布请求,但我得到 socketTimeOutException,我尝试通过设置 client.setTimeOut(50000);仍然遇到同样的错误。

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");
}

});
}

}

我通过 httpclient 尝试了相同的 url,它有效:

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();
}
}

最佳答案

我发现 AsyncHttpClient 实际上默认为 10 秒超时。如果您的请求需要更长的时间,您将看到抛出的 SocketTimeoutException。

调整这个非常简单。只需执行以下操作:

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

关于java - LoopJ Android 异步 Http 客户端 - java.net.SocketTimeoutException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com