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
}
}
有人會知道爲什麼會發生這種情況,以及如何防止它?
請不要給標題添加標籤 –