簡體   English   中英

在Jersey Java中發送和接收JSON到REST WebService

[英]Send and receive JSON to REST WebService in Jersey Java

我是Jersey Java REST WebService框架的新手。 我正在嘗試編寫使用並生成JSON的服務方法。 我的服務代碼如下。 這是最簡單的代碼,僅用於學習目的。

@Path("/myresource")
public class MyResource {

    @Path("/sendReceiveJson")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String sendReceiveJson(String name)
    {
        System.out.println("Value in name: " + name);
        return "{\"serviceName\": \"Mr.Server\"}";
    }

}

以下是JerseyClient代碼。

public class Program {
    public static void main(String[] args) throws Exception{

        String urlString="http://localhost:8080/MyWebService/webresources/myresource/sendReceiveJson";

        URL url=new URL(urlString);
        URLConnection connection=url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("{\"clientName\": \"Mr.Client\"}");
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
        }
        in.close();
}
}

但是當我運行服務然后運行客戶端時,我無法發送/接收JSON數據。 我在connection.getInputStream()處獲得異常

Server returned HTTP response code: 405 for URL: http://localhost:8080/hellointernet/webresources/myresource/sendReceiveJson
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)

請指導我,需要糾正什么,或者我的方向是否錯誤。

您的資源方法注釋為@GET,這意味着任何輸入數據都必須是查詢字符串參數。

在這種情況下,@ Consumes(MediaType.APPLICATION_JSON)並沒有多大意義,因為通過GET僅支持APPLICATION_FORM_URLENCODED。

當客戶端調用setDoOutput(true)時,它可能會將HTTP調用切換為POST,從而導致405 Method Not Allowed。

如果要使用JSON,則應改為使用@POST更改@GET注釋。 如果確實是POST,則您的客戶呼叫應該可以工作。 您可以使用以下方法指定它:

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

不過,該API的級別很低,因此,我強烈建議您改用Jersey的Client API。 參見https://jersey.java.net/documentation/1.17/client-api.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM