Null Pointer Exception: HTTP Entity

孤街醉人 提交于 2019-12-23 18:37:40

问题


I am getting a null pointer exception on the following code, any idea why ?

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static int GET = '1';
    static int POST ='2';

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params, int method) throws URISyntaxException {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        HttpEntity httpentity = null;
        HttpPost postrequest = null;

        try {
            switch (method) {
            case 1: 
                if(params!=null){
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;   
                }

                Log.e("URL", url);
                HttpGet httpGet = new HttpGet(url);
                httpResponse = httpClient.execute(httpGet);
                httpentity = httpResponse.getEntity();          

                break;
            case 2: 
                postrequest = new HttpPost(url);
                postrequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
                httpResponse = httpClient.execute(postrequest);
                httpentity = httpResponse.getEntity();
                if(httpentity !=null)
                {
                    Log.i("RESPONSE", EntityUtils.toString(httpentity));
                }
                else{
                    Log.i("NULL", EntityUtils.toString(httpentity));
                }
                break;
            }
            is = httpentity.getContent();
        } 
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);            
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }

}   

The NPE occurs in the line

is = httpentity.getContent();

Basically, I am accessing this class with a functions class and finally implementing it through another main class.


回答1:


The problem is that your httpentity is null in line where you want to retrieve it's content. You should ensure that your method is either 1, or 2, because you may - by mistake - omit the whole switch statement and run straight to is = httpentity.getContent();.

Also, if you check Android documentation, you can read that:

public abstract HttpEntity getEntity () Added in API level 1

Obtains the message entity of this response, if any. The entity is provided by calling setEntity.

Returns the response entity, or null if there is none

It means that if there's no response entity, getEntity() method will return null. And you made a null check only in your second case. You should check it also in the place where you want to retrieve the content, so your whole try block should look like this:

try {
    switch (method) {
    case 1: 
        if(params!=null){
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;   
        }

        Log.e("URL", url);
        HttpGet httpGet = new HttpGet(url);
        httpResponse = httpClient.execute(httpGet);
        httpentity = httpResponse.getEntity();          

        break;
    case 2: 
        postrequest = new HttpPost(url);
        postrequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        httpResponse = httpClient.execute(postrequest);
        httpentity = httpResponse.getEntity();
        if(httpentity !=null)
        {
            Log.i("RESPONSE", EntityUtils.toString(httpentity));
        }
        else{
            Log.i("NULL", EntityUtils.toString(httpentity));
        }
        break;
    }
    if(httpentity != null)
    {
        is = httpentity.getContent();
        Log.i("RESPONSE", EntityUtils.toString(httpentity));
    } else {
        Log.i("NULL", EntityUtils.toString(httpentity));
    }
} 
catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


来源:https://stackoverflow.com/questions/16097824/null-pointer-exception-http-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!