我有一个简单的类来处理 http 请求。因为自 Android 3.1 以来此任务需要在不同的线程中执行,所以我创建了以下线程阻塞类,女巫使用 get 等待请求完成。
第一次工作,但之后我总是超时或只是冻结应用程序。这是我的代码:
class MakeRequest extends AsyncTask<String,Integer,Void>
{
@Override
protected Void doInBackground(String... params) {
DefaultHttpClient cli = new DefaultHttpClient();
try {
String url = params[0].replace(" ", "%20");
HttpResponse resp = cli.execute(new HttpGet(url));
BufferedReader read = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String tmp = "",rezultat = "";
setResult("");
while ((tmp = read.readLine()) != null)
{
rezultat = rezultat + tmp;
}
setResult(rezultat);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setResult("");
return null;
}
return null;
}
}
static public String req(Context ctx,String url,boolean want_resp)
{
if (isOnline(ctx))
{
HttpRequester cc = new HttpRequester();
MakeRequest test = cc.new MakeRequest();
test.execute(url);
if (want_resp)
{
try {
test.get(30000, TimeUnit.MILLISECONDS);
}
catch (Exception e)
{
return "FAIL";
}
return result;
}
else return "OK";
}
else
{
Toast.makeText(ctx, "Internet connection required", Toast.LENGTH_SHORT).show();
setResult("");
return "";
}
}