空指针异常:HTTP实体 [英] Null Pointer Exception: HTTP Entity

查看:136
本文介绍了空指针异常:HTTP实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个空指针异常以下code,任何想法,为什么?

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

}   

NPE 发生在行

is = httpentity.getContent();

基本上,我访问本类与类的功能,最后通过另一个主要的类实现它。

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

推荐答案

的问题是,你的 httpentity 在要检索它的内容一致。你应该确保你的 1 2 ,因为你可能 - 错误 - 忽略整个switch语句,直接运行是= httpentity.getContent();

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

另外,如果你查看​​Android文档,你可以阅读:

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

在API级别公共抽象HttpEntity getEntity()1

public abstract HttpEntity getEntity () Added in API level 1

获得此响应的消息的实体,如果有的话。该实体是
  通过调用setEntity提供。

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

返回响应实体或null如果没有

Returns the response entity, or null if there is none

这意味着,如果没有响应实体, getEntity()方法将返回。而你只在你的第二个案例做了一个空检查。你也应该检查一下在您要检索的内容的地方,让你的整个try块应该是这样的:

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

这篇关于空指针异常:HTTP实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆