ali
ali

Reputation: 25

Error parsing data org.json.JSONException: End of input at character 0 of

I'm trying to parse JSON data which is coming from this url.

But I am getting these errors:

03-27 16:48:21.019: E/Buffer Error(23717): Error converting result java.lang.NullPointerException

03-27 16:48:21.059: E/JSON Parser(23717): Error parsing data org.json.JSONException: End of input at character 0 of

Wwhen I debug my code; getJsonFromUrl() method returns null jobject. Here is the JSONParser class which I used. What's causing the error?

public class JSONParser {

    static InputStream iStream = null;
    static JSONArray jarray = null;
    static JSONObject jObj= null;
    static String json = "";

    public JSONParser() {
    }



    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);



        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            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");
            }
            iStream.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

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

        // return JSON String
        return jObj;

    }
}

I'm making the call for this method from another class using these lines. (url parameter is defined at top)

  JSONParser jParser = new JSONParser();
  final JSONObject jobject = jParser.getJSONFromUrl(url);

Upvotes: 1

Views: 12649

Answers (1)

vzamanillo
vzamanillo

Reputation: 10514

You are trying to get the JSON content using a HTTP POST method instead of the appropiated GET method (W3schools.com GET vs.POST), modify your source code to simplify and fix your HTTP request

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);

try {
    HttpResponse httpResponse = httpClient.execute(get);
    String json = EntityUtils.toString(httpResponse.getEntity());
    System.out.println(json);
    ....
    ....

} catch (Exception e) {
    ....
}

Upvotes: 1

Related Questions