AsyncTaks HTTP请求超时和异常处理

时间:2012-11-28 00:21:12

标签: java android

我正在向Facebook图形API发出HTTP-get请求。

大约1/5的时间我的代码永远不会到达Log.i("debug", "resp");。没有异常抛出。不应该吗?或者它默认是一个非常长的超时?

如果我添加自定义超时(见下文),我会抛出异常。但即使我的代码包含在try + catch语句中,我的应用程序崩溃(就像任何未处理的异常一样),而不是让我处理onPostExecute()中的错误。为什么我不接受这个方法?

protected Map<String, Integer> doInBackground(Void... params) {

    Map<String, Integer> result = new HashMap<String, Integer>();

    try {

        HttpGet get = new HttpGet("https://graph.facebook.com/....etc");

        //final HttpParams httpParams = httpclient.getParams();
        //HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        //HttpConnectionParams.setSoTimeout(httpParams, 5000);

        HttpResponse response = httpclient.execute(get);
        Log.i("debug", "resp");  

        HttpEntity resEntityGet = response.getEntity();

        //do stuff with resEntityGet           

        return result;            

    } catch (Exception e) { 
        Toast.makeText(mainActivity, "Error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        return null;
    }
}

protected void onPostExecute(Map<String, Integer> result) {

    if(result != null){
        //use the result data
    } else {
        //exception occured
    }
}

5 个答案:

答案 0 :(得分:1)

如果您将Toast方法发布到UI线程,则可以显示doInBackground。有几种方法可以做到,但这是一种方式:

mainActivity.runOnUiThread( new Runnable() {

    @Override
    public void run() {
        Toast.makeText(mainActivity, "Error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
    }
} );

您需要制作Exception变量final

答案 1 :(得分:0)

自己想出来。事实证明,您无法在doInBackground()中创建祝酒词。希望这有助于其他人。

答案 2 :(得分:0)

我也面临同样的问题,即我以这种方式处理异常

public class ServerCheckingActvity extends Activity{
    ProgressDialog  progress;
    static String constant="";
    Map<String, Integer> result;
    @Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     new MyAsynchTask().execute();
}

private  class MyAsynchTask extends AsyncTask<Void,Void,String>{
    @Override
    protected void onPreExecute(){
           progress=new ProgressDialog(ServerCheckingActvity.this);
           // progress.setTitle(" DATA RETRIVEING");
            progress.setMessage("please wait........");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setCancelable(true);
            progress.show();
            super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {
        String view="";

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpGet get = new HttpGet("www.facebook .com/...........");

            //final HttpParams httpParams = httpclient.getParams();
            //HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
            //HttpConnectionParams.setSoTimeout(httpParams, 5000);

            HttpResponse response =httpClient.execute(get);
            Log.i("debug", "resp");  

            HttpEntity resEntityGet = response.getEntity();

            //do stuff with resEntityGet           

           // assigen ur value to result map object here;    
            result = new HashMap<String, Integer>();


        } catch (Exception e) { 
            constant="Exception";
            //Toast.makeText(mainActivity, "Error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
            //return null;
        }
        return view="from doing background";
    }
    @Override
    protected void onPostExecute(String view ){
        if(constant=="Exception"){
            constant="";
            Toast.makeText(getApplicationContext(), "server problem", Toast.LENGTH_LONG).show();

        }else if(result != null){
            //use the result data
        } else {
            //exception occured
        }
    }

}

答案 3 :(得分:0)

catch (Exception ex) {
       // execep is here string variable u declare in globally
       execep=ex.getMessage();
      runOnUiThread( new Runnable() {
   @Override
public void run() {
  Toast.makeText(  getApplicationContext(), "Error: " +execep, Toast.LENGTH_LONG).show();
                                        }} );

                               }//catch

答案 4 :(得分:0)

您的代码是正确的,但它并不清晰且安全。如果未设置超时,则将其设置为默认值0.超时值为零将被解释为无限超时。在这种情况下,当响应数据因任何问题而出现问题时,您的客户端会被中断或者什么都不知道。在案例2 - 更糟糕的情况下 - 客户端不会抛出任何异常,您的程序将永远存在。 解决此问题,您应该在将所有内容发送到服务器或将其发布到服务器时设置超时。它是安全的。 我并不完全知道客户永远生活的原因,没有任何例外。我认为这是服务器问题或网络问题。 希望可以帮到你。