Get JSON of web service in JAVA

1

I am starting in the programming of online databases and its communication with a local application such as a JAVA or Android desktop application.

My question is this:

Having a PHP service configured in a URL that returns all the data in the database in a JSON, how can I get them for example in JAVA? How do I connect and make the request to save them in a local variable?

PS: You can click on the link to verify that I am returning a valid JSON.

Thank you very much in advance.

    
asked by Alex 25.10.2017 в 14:33
source

1 answer

1

I have solved it in this way, in case someone is worth it. It works with pearls obtaining as output from the system.out the JSON value mentioned above.

package consumidor;

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 a {

  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("LA URL DE TU SERVICIO");
    System.out.println(json.toString());
  }
}
    
answered by 25.10.2017 / 14:54
source