我正在尝试用Java创建HTTP PATCH请求,但尽管我付出了努力,但这并不起作用。 我正在尝试修补一个Json,这是我的代码:
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){
}
当我执行此请求时,我得到了
&#34; 400错误:请求的标题名称无效&#34;。
当我使用Postman执行此请求时,这工作正常。
我对HTTP请求很陌生,所以不要犹豫,询问您是否需要更多详细信息。
答案 0 :(得分:1)
StringEntity.setContentEncoding
用于设置编码类型,
您应该使用StringEntity.setContentType
来设置 ContentType
答案 1 :(得分:1)
问题-
RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject("http://localhost:8080/employee/1", requestBody, String.class);
解决方案-
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject("http://localhost:8080/employee/1?_method=patch", requestBody, String.class);