2012-02-10 67 views
1

在尝试调用Web服务并获取相应的json对象时,我得到一个致命异常。我完全不知道在哪里看,以及要纠正哪些错误。获取“致命异常:AsyncTask#2”。我不知道是什么原因造成的

[Screendump of the exception in question](http://i.imgur.com/EZcbW.png)

编辑:

private class CallServiceTask extends AsyncTask<Object, Void, JSONObject> 
{ 

    protected JSONObject doInBackground(Object... params) 
    { 
     HttpGet req = (HttpGet) params[0]; 
     String url = (String) params[1]; 

     return executeRequest(req, url); 
    } 
} 

而这里的所谓在doInBackground executeRequest方法:

private JSONObject executeRequest(HttpGet request, String url) 
{ 
    HttpClient client = new DefaultHttpClient(); 
    JSONObject jsonObj = null; 
    client = getNewHttpClient(); 

    HttpResponse httpResponse; 

    try { 
     httpResponse = client.execute(request); 

     HttpEntity entity = httpResponse.getEntity(); 

     if (entity != null) { 

      InputStream instream = entity.getContent(); 
      String response = convertStreamToString(instream); 
      try { 
       jsonObj = new JSONObject(response); 
      } catch (JSONException e1) { 
       e1.printStackTrace(); 
      } 

      // Closing the input stream will trigger connection release 
      instream.close(); 
     } 

    } catch (ClientProtocolException e) { 
     client.getConnectionManager().shutdown(); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     client.getConnectionManager().shutdown(); 
     e.printStackTrace(); 
    } 
    return jsonObj; 
} 
+0

问题是一类投放问题。你可以在你的asynctask中的'doInBackground'方法中发布代码。谢谢 – 2012-02-10 13:34:14

+0

我认为你放错了代码。将代码粘贴到您称为CallServiceTask.excecute(...)的地方;来自RestClient.java。为了帮助我们需要RestClient.java – 2012-02-10 14:01:13

回答

3

就看你的logcat的堆栈跟踪(在这种情况下),它会告诉你所有你需要知道的例外是什么以及是什么造成的:

螺纹与未捕获的异常

退出告诉你一个异常被抛出,你的代码不处理

在执行doInBackground()

出错这告诉你你的Async任务中的doInBackground()函数抛出了这个未处理的异常

产生的原因:java.lang.ClassCastException ... HttpPost ...(RestClient.java:275)

这告诉你,你遇到了一个ClassCastException,从产生HttpPost在该源文件中的第275行调用。

编辑:

应该已经阅读堆栈跟踪更仔细地......作为HandlerExploit已经发布就这么的投掷的错误,当你期待的HttpPost一个HTTPGET ......但下面的调试方法仍然有效:

如果使用e.getMessage()添加额外的catch(ClassCastException e),您很可能会看到一个有用的错误消息,更详细地描述了该问题。在这种情况下,当我发现一个意想不到的异常被抛出,我倾向于添加一个临时的'catch all'(catch(Exception e){e.printStackTrace()}),并在e .printStackTrace(),所以我可以看到关于异常的所有细节......可能不是最有效的方法,但它是在黑暗中开始的一个开始!

+0

无论他是否包装它都没关系,他仍然会看到完整的堆栈跟踪。 – HandlerExploit 2012-02-10 15:20:31

0

我最好的猜测是:

HttpGet req = (HttpGet) params[0]; 

返回一个HttpPost而不是HttpGet的。

请张贴在那里你调用new CallServiceTask().execute();

相关问题