Shreyas SG
Shreyas SG

Reputation: 388

REST API | Jersey jar | 405 error

I am trying to do automate REST API through Java. For this, I am using Jersy jar. I googled enough and was able to write a code that doesn't throw any exception. However, I am always getting 405 - Method not allowed error response when I try to reach my project's endpoint and post the request. Same endpoint returns success response on Soap UI. And there are no headers required. Media type is JSON.

Basically, I just want to do the SOAP UI operation, but through Eclipse. PS: I'm novice, any help is appreciated.

package sample;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.glassfish.jersey.client.JerseyInvocation.Builder;

public class Sample 
{
    public static void main(String a[])
    {

        Client client = ClientBuilder.newClient();
        WebTarget resource = client.target("https://endpoint-url/Resource");
        Form form = new Form();
        form.param("name", "bond");
        form.param("ID", "007");

        Builder request = (Builder) resource.request();
        request.accept(MediaType.APPLICATION_JSON);

        Response response = request.get();
        if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) 
        {
            System.out.println("Success! " + response.getStatus());
            System.out.println(response.readEntity(String.class));
        } 
        else 
        {
            System.out.println("ERROR! " + response.getStatus());    
//          System.out.println(response);
            System.out.println(response.readEntity(String.class));
        }
    }

}

Upvotes: 0

Views: 473

Answers (2)

Shreyas SG
Shreyas SG

Reputation: 388

Finally, I found the code here that worked wonders for me :)

Below is the working code:

package sample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClient
{

    private static final String targetURL = "https://endpoint-url/Resource";

    public static void main(String[] args)
    {

        try {

            URL targetUrl = new URL(targetURL);

            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/json");

            String input = "{\"name\":\"bond\",\"Id\":007}";

            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();

            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
                    (httpConnection.getInputStream())));

            String output;
            System.out.println("Output from Server:\n");
            while ((output = responseBuffer.readLine()) != null) {
                System.out.println(output);
            }

            httpConnection.disconnect();

          } catch (MalformedURLException e) {

            e.printStackTrace();

          } catch (IOException e) {

            e.printStackTrace();

         }

        }    
}

Upvotes: 0

tech2504
tech2504

Reputation: 977

The issue at accept,get resource instead of Post resource you aren't passing form parameter to resource method. That is reason getting issues.Check below

public class Sample  {
        public static void main(String a[])
        {

            Client client = ClientBuilder.newClient();
            WebTarget resource = client.target("https://endpoint-url/Resource");
            Form form = new Form();
            form.param("name", "bond");
            form.param("ID", "007");
            Builder request = (Builder) resource.request();
            request.accept(MediaType.APPLICATION_JSON);         
    Response response = request.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED));
            if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) 
            {
                System.out.println("Success! " + response.getStatus());
                System.out.println(response.readEntity(String.class));
            } 
            else 
            {
                System.out.println("ERROR! " + response.getStatus());     //          System.out.println(response);
                System.out.println(response.readEntity(String.class));
            }
        }

    }

Upvotes: 1

Related Questions