Issue
I recently encountered some problems with java.net.http.HttpClient that comes with JDK 11. I don't know how to use file upload. Found the ofInputStream() in java.net.http.BodyPublishers. I don't know if I using this method file upload. Here are the examples I wrote.
public HttpResponse<String> post(String url, Supplier<? extends InputStream> streamSupplier, String... headers) throws IOException, InterruptedException {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url))
.headers(headers)
.POST(null == streamSupplier ?
HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofInputStream(streamSupplier));
HttpRequest request = builder.build();
log.debug("Execute HttpClient Method:『{}』, Url:『{}』", request.method(), request.uri().toString());
return client.send(request, HttpResponse.BodyHandlers.ofString());
}
Solution
The java.net.http.HttpClient
handles bytes supplied through the BodyPublisher
as raw body data, without any interpretation. Whether you use HttpRequest.BodyPublishers::ofFile(Path)
or HttpRequest.BodyPublishers::ofByteArray(byte[])
is therefore semantically irrelevant: what changes is simply how the bytes that will be transmitted are obtained.
In case of file upload - your server probably expects that the request body will be formatted in certain ways. It might also expect some specific headers to be transmitted with the request (such as Content-Type
etc). The HttpClient
will not do that magically for you. This is something you need to implement at the caller level.
Answered By - daniel Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.