在我的应用程序中,我必须从4个不同的url中获取数据,然后在完成获取数据后,我必须以特定的顺序显示项目。我正在使用HttoPost发送邮件请求。我在不同的线程中发送4个请求。当线程获取数据时,它会增加一个计数。当计数达到4时,意味着所有4个线程都已获取数据。问题是,有时四个线程中有一个没有响应,这意味着defaultHttpClient.execute(post)不会返回。因此,我的计数并没有达到4,即使它没有抛出异常,只显示等待对话框。我希望在固定的时间后,无论是否从服务器得到响应,它都必须返回。知道吗?
它不起作用。我正在使用以下类:
public class ConnectionManager {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
public ConnectionManager(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void addParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void addHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public String sendRequest() throws Exception {
String serverResponse = "";
HttpPost httpPostRequest = new HttpPost(url);
httpPostRequest.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
//add headers
for(int i = 0; i < headers.size(); i++) {
StringEntity entity = new StringEntity(headers.get(i).getValue(),"UTF-8");
httpPostRequest.setEntity(entity);
}
if(!params.isEmpty()){
HttpEntity httpEntity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
httpPostRequest.setEntity(httpEntity);
}
serverResponse = executeRequest(httpPostRequest);
return serverResponse;
}
private String executeRequest(HttpUriRequest request) throws Exception {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 10000);
DefaultHttpClient client = new DefaultHttpClient(params);
HttpResponse httpResponse;
String serverResponse = "";
httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
serverResponse = convertStreamToString(instream);
instream.close();
}
Log.d("server response", serverResponse);
return serverResponse;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}