java - http POST 请求 JSON 对象中的空指针异常错误

标签 java android json apache http-post

我正在编写 android 代码并使用 httpClient 发送 http POST 请求。它在行中给了我一个空点错误

 httpEntity = httpResponse.getEntity();

我使用了 log cat,发现我的代码停在上面提到的那一行。请帮我解决这个问题。提前致谢。

我的代码是建立http客户端在文件serviceHandler中:

package com.example.manumaheshwari.vigo;

/**
 * Created by ManuMaheshwari on 30/06/15.
 */

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

StringBuilder sb;


public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {

            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded ");

            if (params != null) {

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
                }
                catch (UnsupportedEncodingException e) {
                    // writing error to Log
                    e.printStackTrace();
                }
                // Making HTTP Request
                try {

                    HttpResponse response = httpClient.execute(httpPost);

                    // writing response to log
                    Log.d("Http Response:  ", response.toString());




                } catch (ClientProtocolException e) {
                    // writing exception to log
                    e.printStackTrace();

                } catch (IOException e) {
                    // writing exception to log
                    e.printStackTrace();
                }

            }


        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }


        httpEntity = httpResponse.getEntity();


        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

我的主要 Activity 代码如下:

package com.example.manumaheshwari.vigo;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends ListActivity {

private ProgressDialog pDialog;

// URL to get pending rides JSON
private static String url = "http://128.199.206.145/vigo/v1/displayalldrivers";

// JSON Node names
private static final String TAG_SOURCE = "source";
private static final String TAG_DESTINATION = "destination";
private static final String TAG_DRIVER_ID = "driver_id";
private static final String TAG_NAME = "name";

// pending rides JSONArray
JSONArray pendingRides = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> pendingRidesList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    pendingRidesList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Calling async task to get json
    new GetRides().execute();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetRides extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }
    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("contractor_id", "1"));



        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePairs);

        Log.d("Response: "  , "> " + jsonStr);

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                pendingRides = jsonObj.getJSONArray("driver");

                // looping through All Contacts
                for (int i = 0; i < pendingRides.length(); i++) {
                    JSONObject c = pendingRides.getJSONObject(i);

                    String source = c.getString(TAG_NAME);
                    String destination = c.getString(TAG_DRIVER_ID);

                    // tmp hashmap for single contact
                    HashMap<String, String> pendingRide = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    pendingRide.put(TAG_NAME, source);
                    pendingRide.put(TAG_DRIVER_ID, destination);


                    // adding pending ride to pending ride list
                    pendingRidesList.add(pendingRide);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, pendingRidesList,
                R.layout.list_view, new String[] { TAG_SOURCE, TAG_DESTINATION,}, new int[] { R.id.source,R.id.destination});

        setListAdapter(adapter);
    }

}
}

最佳答案

似乎httpResponse是null,因为在POST方法中你没有给它赋值。所以在POST方法中,改变

HttpResponse response = httpClient.execute(httpPost);

// writing response to log
Log.d("Http Response:  ", response.toString());

httpResponse = httpClient.execute(httpPost);

 // writing response to log
Log.d("Http Response:  ", httpResponse.toString());

关于java - http POST 请求 JSON 对象中的空指针异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167341/

相关文章:

Android getParentFragment() 直接从布局中膨胀 fragment 时为空

javascript - JSON动态Javascript解析 "undefined"

php - 获取 MySql 查询的响应

java - 如何将 google 文档与我的 java web 应用程序集成?

javascript - 通过自定义 Cordova 方案获得安全来源

java - 无法运行简单的 hello world

android - 如何从 Android 中的 SimpleExoPlayerView 中删除下一个和上一个按钮

javascript - JSON 响应中的非法字符

java - 在标准变量上使用常量是否使用更少的内存?

java - 无效的 XML 字符(Unicode : 0x0) Error - Solving the Problem