zied123456
zied123456

Reputation: 255

405 Error when sending HTTP request throw JAVA

I try to send http request and get the result with a Java code

this is the Server side:

public class Testws {
@GET
    @Path("/test/{id}")
    @Produces("application/xml")
    public Integer getAssets(@PathParam("id") int id){
        }
}

And this is the Client side:

URL url = new URL("http://xxx/route/test/1");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.connect();
final int responseCode = connection.getResponseCode();

when i run this java code i got an 405 status code but when i put the link (http://xxx/route/test/1) directly in the browser it works fine i got 200 as a response code. How can i fix this ?

Upvotes: 1

Views: 2081

Answers (1)

Arnaud
Arnaud

Reputation: 17524

Your error means that you query the server with the wrong HTTP method.

What you paste in your browser will be sent as GET method.

Your code doesn't use GET, so to force an HTTP method, use HttpConnection.setRequestMethod

Alternatively, setDoOutput(true) won't make you use GET, see this topic : What exactly does URLConnection.setDoOutput() affect?.

Remove this line and you will use the default HTTP method, which is GET.

public void setRequestMethod(String method) throws ProtocolException

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions. The default method is GET.

Upvotes: 1

Related Questions