我正在从我的Android设备执行HTTP Post
,但出于某种原因,post
会在几秒内执行,但屏幕仍然会冻结18或20秒。
我正在使用的代码是:
public boolean CommentPost(String comment, String requestId, String deviceId){
List<NameValuePair> params = new ArrayList<NameValuePair>(6);
params.add(new BasicNameValuePair("requestId", requestId));
params.add(new BasicNameValuePair("comment", URLEncoder.encode(requestId)));
params.add(new BasicNameValuePair("deviceId", URLEncoder.encode(deviceId)));
return ExecutePost(params, "Comment/Add");
}
private boolean ExecutePost(List<NameValuePair> params, String url){
String queryString = RewriteParams(params);
url = BaseURL + url + queryString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
return true;
} catch (ClientProtocolException e) {
return false;
} catch (IOException e) {
return false;
}
}
我使用ajax和一些Http客户端(如邮递员)测试了行为,并且请求执行时间不到1或2秒并获得响应。 为什么它在android中说更多时间?
答案 0 :(得分:2)
class Check extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
//Add main arguments here; Connection that reffers to other methods but
String queryString = RewriteParams(params);
url = BaseURL + url + queryString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
return true;
} catch (ClientProtocolException e) {
return false;
} catch (IOException e) {
return false;
}
return null;
}
}
并执行如下:
new Check().execute("http://website.com");
如果需要,您可以在那里添加网址。如果它是固定链接,则不是必需的。
您添加了以便可以在主线程上运行连接内容,但我相信您的线程没有正确构建。它可以这样解释:
while(bool = true){
connection code
}
rendering code
在连接并完成所有这些操作时,由于连接要求,其他任务无法执行。运行异步允许您连接而不会干扰主线程。
如果你需要不同于String,Integer和Boolean的参数,请记住第一个变量是doInBackground中的params,最后一个参数是返回值