I tried to build an app in android studio which does json parsing from a URL server with ports (example: http://xxx.xxx.xxx.xxx:xxxx). So I found 3 methods such as asynctask, volley and okhttp. But the problem is everytime I parse it with these methods, the same exception always occurred.
java.net.ProtocalException: Unexpected status line: HTTP/1.1 Cache-Control:no-cache
Here is my code
class GetJSON extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please Wait"); pDialog.setCancelable(false); pDialog.show(); viewId = (TextView) findViewById(R.id.ID) ; } @Override protected String doInBackground(Void... voids) { try { URL url = new URL(urlWebService); HttpURLConnection con = (HttpURLConnection) url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String json; while ((json = bufferedReader.readLine()) != null) { sb.append(json + "n"); } JSONObject data = new JSONObject(sb.toString().trim()); return sb.toString().trim(); } catch (final Exception e) { e.printStackTrace(); resp = e.getMessage(); runOnUiThread(new Runnable() { @Override public void run() { Toast toast = Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_VERTICAL, Gravity.CENTER_HORIZONTAL, 0); toast.show(); } }); } return null; } @Override protected void onPostExecute(String rawData) { super.onPostExecute(rawData); if (pDialog.isShowing()) pDialog.dismiss(); viewId.setText(rawData); } }
So is there any method to do this parsing? Or any solution?
Advertisement
Answer
Okay so apparently the problem was not with the code I am using, but the server API’s responses. The server didn’t response when I hit the API but now it’s working perfectly fine!