I have a simple class to handle http requests. Because this task needs to be performed in a different thread since Android 3.1 I have created the followin thread blocking class witch uses get to wait to the request to complete.
First time it works but after that I always get the time out or just freezes the application. Here is my code:
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 "";
}
}
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.So it blocks the UI.
This will make your main thread wait for the result of the AsyncTask at most 30000 milliseconds.