这种情况很少发生,而且我无法重现它,但是下面的代码有时会从没有主机的情况下出现异常。这是代码:
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
}
}
有谁知道为什么会发生这种情况以及如何防止它?