gpt4 book ai didi

android - 在httprequest android中设置超时

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:26 25 4
gpt4 key购买 nike

我正在使用以下代码通过 http 请求从服务器获取数据。

HttpClient client = new DefaultHttpClient();
String URL = urlGenerator();

StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());

HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();

if(status == 200){
...
}

它工作正常。但如果手机连接到 wifi 或 gprs 3g 但互联网无法正常工作或互联网连接不存在,我想在上面的代码中使用超时功能。

说 3 秒后我想显示超时请重试..我怎么做。如果超时,我想在 textviw 连接超时中显示文本。我该怎么做请帮忙

最佳答案

您可以按如下方式进行:

try{     
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 6000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
} catch (ConnectTimeoutException e) {
//Here Connection TimeOut excepion
Toast.makeText(xyz.this, "Your connection timedout", 10000).show();
}

关于android - 在httprequest android中设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18207265/

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