Nefarious62
Nefarious62

Reputation: 171

HTTP PATCH request in Java

I am trying to make a HTTP PATCH request in Java, but despite my efforts this is not working. I am trying to PATCH a Json, here is my code:

    HttpResponse response = null;
    BufferedReader rd = null;
    StringBuffer result = new StringBuffer();
    String line = "";

    HttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch("http://myURL");

    JsonArrayBuilder Abuilder = Json.createArrayBuilder();
    JsonObjectBuilder oBuilder = Json.createObjectBuilder();
    for(int i=0;i<48;i++){
        Abuilder.add(i+1);
    }
    oBuilder.add("date", "2016-09-08");
    oBuilder.add("values",Abuilder);

    JsonObject jo = Json.createObjectBuilder().add("puissance", Json.createObjectBuilder().add("curves",Json.createArrayBuilder().add(oBuilder))).build();

    try{            
        //Execute and get the response.

        StringEntity params =new StringEntity(jo.toString());

        params.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPatch.setEntity(params);

        response = httpclient.execute(httpPatch);

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                        result.append(line);
        }

    }catch(Exception e){

    }

When I execute this request, I get a

"400 Error: The request has an invalid header name".

When I execute this request using Postman, this is working fine.

I am quite new at HTTP requests so do not hesitate to ask if you need more details.

Upvotes: 0

Views: 24055

Answers (2)

Dhammadip
Dhammadip

Reputation: 87

Problem-

RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject("http://localhost:8080/employee/1", requestBody, String.class);

Solution-

RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject("http://localhost:8080/employee/1?_method=patch", requestBody, String.class);

Upvotes: 0

Roman.Luo
Roman.Luo

Reputation: 63

StringEntity.setContentEncoding is used to set the Encoding type,

You should use StringEntity.setContentType to set the ContentType

Upvotes: 2

Related Questions