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

时间:2015-07-01 16:53:34

标签: java android json apache http-post

我正在使用httpClient进行android编码并发送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;

}

}

我主要活动的代码如下:

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

}
}

1 个答案:

答案 0 :(得分:1)

似乎httpResponse为空,因为在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());