gpt4 book ai didi

java - 我收到 HttpResponse 但 responce.getEntity().getContent() 显示 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 05:55:38 25 4
gpt4 key购买 nike

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

结果 = 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());
}

关于java - 我收到 HttpResponse 但 responce.getEntity().getContent() 显示 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com