14

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?

moosavi
  • 174
  • 1
  • 2
  • 12

3 Answers3

31

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();
}
Lin
  • 497
  • 5
  • 15
Asad Haider
  • 504
  • 1
  • 5
  • 17
  • 2
    Nice solution, doesn't require importing the apache http client! – RestingRobot Apr 19 '17 at 23:18
  • At least two major errors here. 1. `urlConnection.setDoOutput(true);` changes request to `POST` method. 2. It effectively executes two requests, `new InputStreamReader(url.openStream()` opens `url` once again, disregarding `urlConnection` and all of its properties. 3. `sb.append(line + "\n")` constructs an excess `String`. – Victor Sergienko Sep 10 '17 at 22:30
14

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" );
}
Ijas Ahamed N
  • 5,632
  • 5
  • 31
  • 53
  • 3
    Where to find the HttpClient? What package I have to include? – Tarion Mar 07 '17 at 15:07
  • 2
    @Tarion just add `useLibrary 'org.apache.http.legacy'` in your app level build.gradle file in `android` block above `defaultConfig`. – Mohammedsalim Shivani May 27 '17 at 10:07
  • this is a deprecated method. Android studio will give you warning over it. Consider using volley for network requests. see https://developer.android.com/training/volley/simple – kPieczonka Jan 14 '19 at 16:51
0
try {
            String line, newjson = "";
            URL urls = new URL(url);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(urls.openStream(), "UTF-8"))) {
                while ((line = reader.readLine()) != null) {
                    newjson += line;
                    // System.out.println(line);
                }
                // System.out.println(newjson);
                String json = newjson.toString();
               JSONObject jObj = new JSONObject(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
raj
  • 2,088
  • 14
  • 23