Java 如何按预定义的秒数终止AsyncTask请求
我试图创建一个处理程序,如果服务器在20秒内没有响应,它将终止http请求。我想知道从异步任务类中实现这一点的最佳方法是什么 这是我的代码:Java 如何按预定义的秒数终止AsyncTask请求,java,android,Java,Android,我试图创建一个处理程序,如果服务器在20秒内没有响应,它将终止http请求。我想知道从异步任务类中实现这一点的最佳方法是什么 这是我的代码: public class DBcontroller extends AsyncTask <List<NameValuePair>, Void, String>{ private static String url = ""; private Context context = null ; public
public class DBcontroller extends AsyncTask <List<NameValuePair>, Void, String>{
private static String url = "";
private Context context = null ;
public AsyncResponse delegate= null;
private PropertyReader propertyReader;
private Properties properties;
public DBcontroller(Context mycontext,AsyncResponse myresponse) {
context = mycontext;
delegate = myresponse;
propertyReader = new PropertyReader(context);
properties = propertyReader.getMyProperties("config.properties");
url = properties.getProperty("url");
}
@Override
protected void onPreExecute() {
super.onPreExecute();
delegate.preProcess();
}
@Override
protected String doInBackground(List<NameValuePair>... params) {
return postDataToServer(params[0]);
}
@Override
protected void onPostExecute(String resStr) {
super.onPostExecute(resStr);
delegate.handleResponse(resStr);
}
private String postDataToServer(List<NameValuePair> list) {
//check
for (int i=0;i<list.size();i++)
Log.d("responseString", list.get(i).toString());
//check
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String responseString = null;
try {
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
Log.d("responseString1", responseString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(responseString!= null)
Log.d("responseString2", responseString);
return responseString;
}
}
公共类DBcontroller扩展异步任务{
私有静态字符串url=“”;
私有上下文=null;
公共异步响应委托=null;
私人财产领头人财产领头人;
私人物业;;
公共数据库控制器(上下文mycontext、异步响应myresponse){
上下文=mycontext;
delegate=myresponse;
propertyReader=新的propertyReader(上下文);
properties=propertyReader.getMyProperties(“config.properties”);
url=properties.getProperty(“url”);
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
proprocess();
}
@凌驾
受保护字符串doInBackground(列表…参数){
返回postDataToServer(参数[0]);
}
@凌驾
受保护的void onPostExecute(字符串resStr){
super.onPostExecute(resStr);
代表HandlerResponse(resStr);
}
私有字符串postDataToServer(列表){
//检查
对于(int i=0;i
HttpUrlConnection有一个setConnectionTimeout()方法,它就是这样做的
HttpURLConnection http = (HttpURLConnection) mURL.openConnection();
http.setConnectTimeout(15000); //timeout after 15 seconds
使用:
您还可以发布一个处理程序,该处理程序将在Url连接上调用disconnect()
new Handler(Looper.getMainLooper()).postDelayed(new Runnable(){
@Override
public void run() {
httpUrlConnection.disconnect();
}
}, 5000);
[编辑]
HttpClient到Url转换伪代码-未测试
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean postToServer(String url, String postData, StringBuilder resultData) throws IOException {
URL at_url = new URL(url);
int responseCode = 0;
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) at_url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream os = httpUrlConnection.getOutputStream();
try {
os.write(postData.getBytes(Charset.forName("UTF-8")));
} finally {
os.flush();
os.close();
}
httpUrlConnection.connect();
String response = "";
responseCode = httpUrlConnection.getResponseCode();
if (responseCode == 200) {
InputStream is = httpUrlConnection.getInputStream();
response = convertStreamToString(is);
// Read is to get results
} else {
InputStream is = httpUrlConnection.getErrorStream();
response = convertStreamToString(is);
// Read is to get error
}
resultData.append(response);
}
finally {
// Cleanup
}
return responseCode == 200;
}
我想这可能会对你有所帮助。HttpClient不推荐使用HttpUrlConnection,或者你可以在设置超时的地方使用okhttp。你也可以去掉for循环中的一些代码,可以将它们保留在外部。你有可能帮我用你在我的代码中建议的HttpUrlConnection替换我的HttpClient对象?@matant我已经添加了d一些代码,你应该很容易适应你的需要。
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean postToServer(String url, String postData, StringBuilder resultData) throws IOException {
URL at_url = new URL(url);
int responseCode = 0;
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) at_url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream os = httpUrlConnection.getOutputStream();
try {
os.write(postData.getBytes(Charset.forName("UTF-8")));
} finally {
os.flush();
os.close();
}
httpUrlConnection.connect();
String response = "";
responseCode = httpUrlConnection.getResponseCode();
if (responseCode == 200) {
InputStream is = httpUrlConnection.getInputStream();
response = convertStreamToString(is);
// Read is to get results
} else {
InputStream is = httpUrlConnection.getErrorStream();
response = convertStreamToString(is);
// Read is to get error
}
resultData.append(response);
}
finally {
// Cleanup
}
return responseCode == 200;
}