通过服务到Web应用程序从Rest客户端请求中检索JSON

时间:2018-05-30 09:17:48

标签: java apache rest http rest-client

我已经让REST客户端向服务器发送http请求,并使用JSON消息接收回复:

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;
    }
}

当我运行上面的函数时,我可以看到返回的JSON。服务器端(API)上的Resonse如下所示:

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

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

如果我查询此链接http://localhost/myProject/rest/employees/getEmployees,我无法获取任何数据,只会收到错误:

  

HTTP状态500 - Servlet的Servlet.init()Jersey REST服务抛出异常

我试图改变它:

@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  ";
    }
}

问题是什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

首先验证您是否在客户端收到回复:

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

如果显示问题是响应。

如果是响应,您可以尝试将响应添加为JSON:

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

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