简体   繁体   中英

Retrieve JSON from Rest Client Request trough Service To Web Application

I've made a REST client sending http request to a server, receiving reply with JSON message:

public class TestClass {
    public static String getData() {
        String output = null;
        try {

            URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/application.json");//my url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);

            while ((output = br.readLine()) != null) {
                System.out.println(output); 
            }

            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in TestClass:- " + e);
        }
        return output;
    }
}

When I run the function above, I can see the returned JSON. Resonse on the server side (API) looks like this:

@Path("/employees") public class employee {

    @GET
    @Path("/getEmployees")
    public String  createNewMassage() {
        return TestClass.getdata();
    }
}

If I query this link http://localhost/myProject/rest/employees/getEmployees , I don't get any data, only errors:

HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception


I tried to change it like:

@Path("/employees")
public class employee {

    @GET
    @Path("/getEmployees")
    public String  createNewMassage() {
        return "WHY THE TEXT SHOW BUT NOT THE REST CLIENT HTTP REQUEST IN JSON  ";
    }
}

What is the issue? How can I resolve the problem?

First verify if you are getting the response in your client:

System.out.println(TestClass.getdata());

If show the problem is the response.

If are the response you can try to add the response as a JSON:

@Path("/employees")
public class JSONService {

    @GET
    @Path("/getEmployees")
    @Produces(MediaType.APPLICATION_JSON) //DEFINE RESPONSE
    public String  createNewMassage() {
       return TestClass.getdata();
    }
    //...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM