【问题标题】:Retrieve JSON from Rest Client Request trough Service To Web Application从 Rest 客户端请求通过服务到 Web 应用程序检索 JSON
【发布时间】:2018-05-30 09:17:47
【问题描述】:

我已经创建了一个 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 Jersey REST 服务的 Servlet.init() 引发异常


我试图改变它:

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

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

【问题讨论】:

  • 在雇员类中你调用TestClass.getdata() 尽管你的TestClass 中的方法被调用getData()(注意大写的d!)
  • 这不是问题。

标签: java apache rest http rest-client


【解决方案1】:

首先验证您是否在客户端收到响应:

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();
    }
    //...

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多