Hamza Amami
Hamza Amami

Reputation: 43

Unable to do a PATCH on w REST API through JAVA

I want to call an API with different method :

The post and get are ok using HttpClient

I'm unable to do the PATCH and delete methods, does anyone implemented such thing ? and how ?

Post Method 1

public static String sendPost(String requestURL, Map<String, String> headers, String postParameters,
        boolean withProxy) throws IOException {

    HttpURLConnection con = createProxyHttpConnection(requestURL, withProxy);
    con.setRequestMethod("POST");
    con.setDoOutput(true);

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());

    }
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(postParameters);
    String response = IOUtils.toString(con.getInputStream(), "UTF-8");

    wr.close();
    con.disconnect();
    return response;

}

Post Method 2

public static HttpResponse sendPostBis(String requestURL, Map<String, String> headers, String payload,
        boolean withProxy) throws IOException {

    StringEntity sEntity = new StringEntity(payload,
            ContentType.APPLICATION_FORM_URLENCODED);

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(requestURL);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.addHeader(entry.getKey(), entry.getValue());

    }
    request.setEntity(sEntity);

    HttpResponse response = httpClient.execute(request);
    return response;

}

I'm using method 1 for POST with params and the Method 2 for POST with json body

Error message (the same that I'll receive if I change method to POST instead of PATCH in SoapUI)

{"error":"No route found for \u0022POST \RESOURCE","message":"No route found for \u0022POST RESOURCE"}

Upvotes: 0

Views: 1211

Answers (2)

Hamza Amami
Hamza Amami

Reputation: 43

Solved :

Change HttpPost request = new HttpPost(requestURL); by HttpPatch request = new HttpPatch(requestURL);

Also there was problem on my url (https), so thanks @Ivan Jadric

Upvotes: 0

Ivan Jadric
Ivan Jadric

Reputation: 32

Without providing any code, my best guess would be that the network over which you are trying to make those PATCH and DELETE requests has blocked those HTTP verbs and thus you are unable to make them. Most network security tools consider any verbs other than GET and POST to be unsafe and do therefore blacklist them

Upvotes: 1

Related Questions