簡體   English   中英

我正在獲取HttpResponse,但是responce.getEntity()。getContent()顯示NullPointerException

[英]I am getting HttpResponse but responce.getEntity().getContent() shows NullPointerException

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM