Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Maybe something failed during the server communication, you should check the servers responsecode before reading the content. Add this code after your <code>httpClient.execute(httpPost);</code></p> <pre><code>int httpStatus = httpResponse.getStatusLine().getStatusCode(); switch( httpStatus ) { case HttpStatus.SC_OK: { HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); // Continue with reading the content here } default: { // here you can print errormessages or information what happened } } </code></pre> <p>The full code for your class could be:</p> <pre><code>public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); int httpStatus = httpResponse.getStatusLine().getStatusCode(); switch( httpStatus ) { case HttpStatus.SC_OK: { try { HttpEntity httpEntity = httpResponse.getEntity(); 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"); } is.close(); json = sb.toString(); } 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()); } } break; } default: { Log.e("JSON Parser", "HttpStatus: "+httpResponse.getStatusLine().getStatusCode() + ", message: " + httpResponse.getStatusLine().getReasonPhrase() ); jObj = null; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jObj; } } </code></pre> <p>This should help you to see what the server is responding, hope I didn<code>t forget a { in the code ;) The 'default' of the switch is your error section, for every server response except</code>200 OK` you will get a log entry with the server response.</p> <p>If you need more cases (e.g. is you like different messages for <code>403 Forbidden</code> Yust add more <code>case HttpStatus.SC_XXXXX</code> blocks. Check wiki if you need more informations about <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes" rel="nofollow">Http Statuscodes</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload