0

这种情况很少发生,而且我无法重现它,但是下面的代码有时会从没有主机的情况下出现异常。这是代码:

public class AddComment extends AsyncTask<String, Void, String> 
{
    @Override
    protected String doInBackground(String... theParams) 
    {
        String myUrl = theParams[0];
        final String comment = theParams[1];
        final String user_id = theParams[2];
        final String problem_id = theParams[3];
        final String recent_topic_id = theParams[4];

        String charset = "UTF-8";           
        String response = null;

        try 
        {                           
            String query = String.format("comment=%s&user_id=%s&problem_id=%s&recent_topic_id=%s", 
                     URLEncoder.encode( comment, charset), 
                     URLEncoder.encode( user_id, charset), 
                     URLEncoder.encode( problem_id, charset), 
                     URLEncoder.encode( recent_topic_id, charset)
                     );             

            final URL url = new URL( myUrl + "?" + query );

            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true); 
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            conn.setUseCaches(false);

            conn.connect();

            InputStream stream = conn.getInputStream();
            byte[] stream_buffer = new byte[8196];
            int readCount;
            StringBuilder stream_builder = new StringBuilder();
            while ((readCount = stream.read(stream_buffer)) > -1) 
            {
                stream_builder.append(new String(stream_buffer, 0, readCount));
            }

            response = stream_builder.toString();       
        } 
        catch (Exception e) 
        {
                           // EXCEPTION HAPPENS HERE
                e.printStackTrace();
        }

        return response;
    }

    @Override
    protected void onPostExecute(String result) 
    {
           if ( result == null )
           {
                  // Do stuff
           }
        }
        else
        {               
      // Do stuff
    }        
}        

有谁知道为什么会发生这种情况以及如何防止它?

4

1 回答 1

1

你是在物理设备上测试这个吗?这可能是由于手机信号不佳,或者与您的设备或模拟器的互联网连接不稳定造成的。这也可以解释为什么你不能复制它。

于 2012-11-06T03:31:31.443 回答