简体   繁体   中英

Getting Error 405 for post request to REST api using Java Jersey api

I wrote a method using Jersey API to make a post request to an api. The api requires the data being posted be in JSON format and has requires a Basic Authorization header however when I run the code below and pass the object it results in the following error

java.lang.RuntimeException: Failed : HTTP error code : 405
at com.shumbamoney.yomoney.SendRequest.send(SendRequest.java:40)

.The java code is below.

 public String send(TransactionRequestObject tRObject){

    Gson gson = new Gson();
    Gson gsonBuilder = new GsonBuilder().create();
    String jsonRObject = gsonBuilder.toJson(tRObject);


    ApiCredentials credentials = new ApiCredentials();
    postUrl = credentials.getURL();
    AgentCode = credentials.getAgentCode();
    Password = credentials.getPassword();
    System.out.println(jsonRObject);

   // jersey code
    try{
        Client client = Client.create();
        WebResource webResource = client.resource(postUrl);
        ClientResponse response = webResource.type("application/json; charset=ISO-8859-1").header(HttpHeaders.AUTHORIZATION, "Basic "+
                AgentCode+":"+Password).post(ClientResponse.class, jsonRObject);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);
    }catch(Exception e){
        e.printStackTrace();
    }

    return "success";
}

Your help is greatly appreciated.

your code did all the things it should: send the request and get the response from the API, so the error doesn't come from your code, it's from the server that you are requesting to.
try using postman to POST to that url, if you still get the 405 error, than you can make sure that the problem is not from ur code.

Thank you everyone for your contributions I really appreciate them. It turns out the issue was on the server that I was requesting to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM