[英]Retrieve JSON from Rest Client Request trough Service To Web Application
我已經制作了一個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)的響應如下所示:
@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 Service的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 ";
}
}
有什么問題 我該如何解決該問題?
首先驗證您是否在客戶端中得到響應:
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();
}
//...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.