Question

I am new to Jersey Java REST WebService framework. I am trying to write a service method which consumes and produces JSON. My service code is below. It is simplest code, just for studying purpose.

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

}

And following is JerseyClient code.

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

But when i run service and then client, i am unable to send/receive JSON data. I get Exception at connection.getInputStream() which is

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)

Please guide me, what needs to correct, or whether i am in wrong direction.

Was it helpful?

Solution

Your resource method is annotated as @GET which means any input data would have to be query string parameters.

In this context @Consumes(MediaType.APPLICATION_JSON) doesn't make a lot of sense as only APPLICATION_FORM_URLENCODED is supported via GET.

When you client calls setDoOutput(true) it probably switches your HTTP call to a POST hence causing the 405 Method Not Allowed.

If you want to consume JSON you should change your @GET annotation with @POST instead. Your client call should then work if it's indeed a POST. You can specify it with the following method:

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

This API is pretty low level though, so I'd highly recommend you use Jersey's Client API instead. See https://jersey.java.net/documentation/1.17/client-api.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top