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;
}
Run Code Online (Sandbox Code Playgroud)
我将把数据发布到下面的数据库中,我附上了剩余的代码,所以请检查并清除我的问题
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();
}
Run Code Online (Sandbox Code Playgroud)
我正在执行NullPointerException以下操作,
result = inputStreamToString(response.getEntity().getContent());。
我不明白实体和内容。有人可以帮助我吗?
您的 HTTP 响应没有实体。这就是为什么getEntity()要回来null。
getEntity()的 JavaDoc声明null可以返回一个值。因此,您应该经常检查这一点。
例如,代替:
result = inputStreamToString(response.getEntity().getContent());
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
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());
}
Run Code Online (Sandbox Code Playgroud)