get json from HttpResponse

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://my.server:8080/android/service.php");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "getjson"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

service.php generates a json string. How would i fetch it from my response? Btw; I’ve icluded the GSON library, can i make use of any methods in it perhaps?

Solutions similar to this one looks pretty ugly, imo: best way to handle json from httpresponse android

  • SDK Location not found in android studio
  • Openssl is not recognized as an internal or external command
  • Object refrence not set to an instance of an object When I create new Android App (Visual Studio)
  • OnClick event only works second time on edittext
  • What is “”?
  • Security exception by accessing the wifi in android
  • There much be better ways, right?

    Any help is appreciated, thanks


    String json = EntityUtils.toString(response.getEntity());

    seems to do the trick. There is just one small issue: The string is wrapped with brackets []. Should i remove them manually? They are generated by php:s json_encode()

    Related posts:

    VideoView seekto() function extremely inconsistent
    Check if ScrollView is higher than screen / scrollable
    Is this custom CursorAdapter for a ListView properly coded for Android?
    Inconsistency detected in RecyclerView, How to change contents of RecyclerView while scrolling
    How to get View in RecyclerView.Adapter for Snackbar?
    Is there a way to hot-deploy delta changes onto an Android device?
  • Set camera width and height phonegap camera
  • How to set the (OAuth token) Authorization Header on an Android OKHTTPClient request
  • How can I create a table with borders in Android?
  • Android doesn't resize my layout when there is a NestedScrollView in the hierarchy
  • Where is Android AVD Manager located on Mac?
  • Set gravity of a View Programmatically
  • 4 Solutions collect form web for “get json from HttpResponse”

    I think the problem you are running into is one similar to my own I just ran into. If you run:

    String json_string = EntityUtils.toString(response.getEntity());
    JSONObject temp1 = new JSONObject(json_string);

    The above code will throw an exception and it looks like the JSON array brackets are to blame. But it’s fine to have a JSON array as the top level element! You just need to use JSONArray() instead of JSONObject:

    String json_string = EntityUtils.toString(response.getEntity());
    JSONArray temp1 = new JSONArray(json_string);

    So you have to know if you are getting a JSONArray or a single dictionary that is a JSONObject in your JSON code.

    If you are used to the iOS/Objective-C JSON parsing libraries they use the same top level element to deal with json dictionaries and json array’s, so moving to the JAVA / Android world confused me about having two types for handling JSON depending on the top level returned.

    With this class, you can get the JSON data from either from a server or from your assets folder. It can be easily changed to only one or the other. If you need a Adapter use the one jgilfelt created here on getHub.

        public void onActivityCreated(Bundle savedInstanceState) {
            Bundle getArgs = this.getArguments();
            new GetJSONTask().execute(URI);
        class GetJSONTask extends AsyncTask<String, Integer, String> {
            protected String doInBackground(String... arg0) {
                String uri = arg0[0];
                InputStream is = null;
                if (uri.contains("http") == true) {// Get JSON from URL
                    try {
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(uri);
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();
                        BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        while ((line = rd.readLine()) != null) {
                            json += line;
                        return json;
                    } catch (Exception e) {
                        return null;
                } else {// Get JSON from Assets
                    Writer writer = new StringWriter();
                    char[] buffer = new char[1024];
                    try {
                        InputStream jsonFile = getActivity().getAssets().open(uri);
                        Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8"));
                        int n;
                        while ((n = != -1) {
                            writer.write(buffer, 0, n);
                    } catch (IOException e) {
                    json = writer.toString();
                    // return JSON String
                    return json;
            protected void onPostExecute(String result) {
                try {
                } catch (JSONException e) {
                    Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show();
        private void showData(String json) throws JSONException {
            JSONObject o = new JSONObject(json);
            JSONArray data = o.getJSONArray("results");

    The problem was in my php file. Removing the container array from the json encoded object made my java code work.

    If I’m returning a JSON string from my web service, I usually want to get it back to a JSON object like so:

    String response = client.getResponse();
        if (responseCode == 200)
             JSONObject obj = new JSONObject(response);                                                             
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.