以下是我获得异常的代码(超时)请提供相同的解决方案或教程。在4.0.4 api级设备上使用
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> params = new LinkedList<NameValuePair>();
> param has some values and a string of bitmap.
HttpResponse response = client.execute(request);
StringBuilder receivedData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null)
{
receivedData.append(line);
}
答案 0 :(得分:0)
试试这个:
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
答案 1 :(得分:0)
首先,你需要了解什么是connectiontimeoutexception:
连接到HTTP服务器或等待来自HttpConnectionManager的可用连接时超时。
这意味着您的设备的互联网无法与HTTP服务器建立连接并且请求超时。你可以做以下两件事来避免这种情况:
在使用以下方法进行HTTP呼叫之前检查是否有活动的互联网连接:
public static Boolean checkActiveInternet(Context activity) {
ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else if (netInfo != null&& (netInfo.getState() == NetworkInfo.State.DISCONNECTED|| netInfo.getState() == NetworkInfo.State.DISCONNECTING|| netInfo.getState() == NetworkInfo.State.SUSPENDED || netInfo.getState() == NetworkInfo.State.UNKNOWN)) {
return false;
} else {
return false;
}
}
为HTTP请求设置更大的超时时间,如下所示:
public static String connect(String url)抛出IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// instream.close();
}
} catch (ClientProtocolException e) {
Utilities.showDLog("connect", "ClientProtocolException:-" + e);
} catch (IOException e) {
Utilities.showDLog("connect", "IOException:-" + e);
}
return result;
}