简体   繁体   English

Java 11 带有PATCH方法的HttpRequest

[英]Java 11 HttpRequest with PATCH method

I try to use the java 11 HttpRequest to call the msgraph webservice using the method PATCH:我尝试使用 java 11 HttpRequest使用 PATCH 方法调用 msgraph webservice:

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.net.URLEncoder;

import java.nio.charset.StandardCharsets;

import groovy.json.JsonSlurper;
import groovy.json.JsonOutput;

access_token = "my_token";

def url = 'https://graph.microsoft.com/v1.0/groups/group_id/drive/items/01P4AIIJ5QTIIAZ2FLEZBIZWRV6KEBIMM5/workbook/worksheets/%7B00000000-0001-0000-0000-000000000000%7D/range(address=\'A1\')'

HttpClient httpClient = HttpClient.newBuilder()
                                    .version(HttpClient.Version.HTTP_2)
                                    .build();

jsonPayloadString = '{"values":["blabla"]}';


jsonPayload = HttpRequest.BodyPublishers.ofString(jsonPayloadString.toString())

HttpRequest request = HttpRequest.newBuilder()
                                 .uri(URI.create(url))
                                 .PATCH(jsonPayload)
                                 .header("Content-Type", "application/json")
                                 .build();

HttpResponse response = httpClient.send(request,HttpResponse.BodyHandlers.ofString());

The error:错误:

No signature of method: jdk.internal.net.http.HttpRequestBuilderImpl.PATCH() is applicable for argument types: (jdk.internal.net.http.RequestPublishers$StringPublisher) values: [jdk.internal.net.http.RequestPublishers$StringPublisher@280a600b] No signature of method: jdk.internal.net.http.HttpRequestBuilderImpl.PATCH() is applicable for argument types: (jdk.internal.net.http.RequestPublishers$StringPublisher) values: [jdk.internal.net.http.RequestPublishers$ StringPublisher@280a600b]

the call itself works great, for instance in Postman.调用本身效果很好,例如在 Postman 中。 But I cannot make it work in groovy/java.但我不能让它在 groovy/java 中工作。

I used previously the HttpUrlConnection but it does not support PATCH.我以前使用过HttpUrlConnection ,但它不支持 PATCH。 Is it actually possible using HttpRequest ?真的可以使用HttpRequest吗?

I could not find any working example of the use of the PATCH method on the Net.我在网上找不到任何使用 PATCH 方法的工作示例。

According to docs, you can use " method " to specify other kind of methods like PATCH, OPTIONS, TRACE, etc.根据文档,您可以使用“ 方法”来指定其他类型的方法,如 PATCH、OPTIONS、TRACE 等。

In your case:在你的情况下:

HttpRequest request = HttpRequest.newBuilder()
                             .uri(URI.create(url))
                             .method("PATCH", jsonPayload)
                             .header("Content-Type", "application/json")
                             .build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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