how to retrive the json data using java

Not applicable

How to retive the JSON data from URL using java code. We have the API url and client_id and client_secret. Need the assitance for this.

0 4 544
4 REPLIES 4

faijahmad
Participant V

Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

package xyz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}

Thanks for your reply Faij Ahmad. But when i tried this code in my server, there is a certificate level issue. is there any sample code for along with certificate sending and get the response or read the JSON data.

It depends on the API how it is accepting client id and client secret to authenticate your request. Try sending details in params or in header. Also check your API specification and documentation.

I have a client id and client secret key. in the above code where we send those details as a params or in header..