protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
我要在下面将数据发布到数据库中,并附上我剩余的代码,因此请检查并清除我的问题
private HttpResponse doResponse(String url) {
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
我在下一行得到
NullPointerException
,result = inputStreamToString(response.getEntity().getContent());
。我不了解实体和内容。有人可以帮助我吗?
最佳答案
您的HTTP响应没有实体。这就是getEntity()
返回null
的原因。
getEntity()的JavaDoc指出可以返回null
值。因此,您应该始终进行检查。
例如,代替:
result = inputStreamToString(response.getEntity().getContent());
你可以这样做:
final HttpEntity entity = response.getEntity();
if (entity == null) {
Log.w(TAG, "The response has no entity.");
// NOTE: this method will return "" in this case, so we must check for that in onPostExecute().
// Do whatever is necessary here...
} else {
result = inputStreamToString(entity.getContent());
}