Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send HttpRequest and get Json response in android? [duplicate]

i want to build an android app for my wordpress website using wp-api plugin. how can i send HttpRequest(GET) and recive response in Json?

like image 773
moosavi Avatar asked Jan 09 '16 08:01

moosavi


2 Answers

Try below code to get json from a URL

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(URL);

HttpResponse response = httpclient.execute(httpget);

if(response.getStatusLine().getStatusCode()==200){
   String server_response = EntityUtils.toString(response.getEntity());
   Log.i("Server response", server_response );
} else {
   Log.i("Server response", "Failed to get server response" );
}
like image 134
Ijas Ahamed N Avatar answered Oct 19 '22 02:10

Ijas Ahamed N


Use this function to get JSON from URL.

public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
    HttpURLConnection urlConnection = null;
    URL url = new URL(urlString);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(10000 /* milliseconds */ );
    urlConnection.setConnectTimeout(15000 /* milliseconds */ );
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    String jsonString = sb.toString();
    System.out.println("JSON: " + jsonString);

    return new JSONObject(jsonString);
}

Do not forget to add Internet permission in your manifest

<uses-permission android:name="android.permission.INTERNET" />

Then use it like this:

try{
      JSONObject jsonObject = getJSONObjectFromURL(urlString);
      //
      // Parse your json here
      //
} catch (IOException e) {
      e.printStackTrace();
} catch (JSONException e) {
      e.printStackTrace();
}
like image 31
Asad Haider Avatar answered Oct 19 '22 01:10

Asad Haider