如何使用 java 通过 HttpPost 发送空二进制数据

问题描述 投票:0回答:2

我想从 curl 实现 HTTP post。

curl $CURL_OPTS -X POST --data-binary {} -s -K <(cat <<< "-u micromdm:$API_TOKEN") "$SERVER_URL/$endpoint"

上面的 curl 命令发送空的二进制数据。

我知道如何发送字符串数据。

发送字符串数据

try {
            CloseableHttpClient httpClient = null;
            try {
                httpClient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(url);

                httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
                httpPost.addHeader("Accept", "application/json;charset=utf-8");
                httpPost.addHeader("Authorization", "XXXXXXXX");

                StringEntity se = new StringEntity(jsonstring, "UTF-8");
                httpPost.setEntity(se);

                HttpResponse httpResponse = httpClient.execute(httpPost);
            catch () {
            }
catch () {
}

但是如何发送空的二进制数据呢?

尝试

                ByteArrayEntity byteArrayEntity = [];
                httpPost.setEntity(byteArrayEntity, ContentType.DEFAULT_BINARY);

这不是工作。

我读了一些不是正确解决方案的文章。

http-post-in-java-with-file-upload

如何从 spring 处理的后请求中获取原始二进制数据

使用 httppost 上传二进制数据

httpclient-post-http-request

类似的相关文章很多,但是我没有找到解决办法。谁能给我这个代码示例?谢谢。

java http-post httpclient
2个回答
1
投票

您提供的代码是json类型的,不是binary类型的:

httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

如果你想要一个空的 json 请求体,做:

StringEntity se = new StringEntity("{}", "UTF-8");

这相当于

 --data-binary {}

“application/octet-stream”是一种通用的二进制数据类型,这意味着它可以用来表示任何类型的二进制数据。当数据的内容类型未知或传输的数据不适合任何其他特定 MIME 类型时,通常使用此 MIME 类型。它通常用于传输文件或原始二进制数据。

对于二进制,使用:

httpPost.addHeader("Content-Type", "application/octet-stream");

并使用空的 inputStream 初始化实体:

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.HttpClientBuilder;
....
public static void main(String[] args) throws IOException {
    
    String url = "https://example.com/api/binary-endpoint";
    
    // create HttpClient instance
    HttpClient httpClient = HttpClientBuilder.create().build();
    
    // create HttpPost instance with URL
    HttpPost httpPost = new HttpPost(url);
    
    // create empty HttpEntity with binary content type
    HttpEntity entity = new InputStreamEntity(IOUtils.toInputStream(""), ContentType.APPLICATION_OCTET_STREAM);
    
    // set entity to request
    httpPost.setEntity(entity);
    
    // send request
    httpClient.execute(httpPost);
}

0
投票
byte[] emptyData = new byte[0];

HttpPost httpPost = new HttpPost("http://example.com/upload");

httpPost.setEntity(new ByteArrayEntity(emptyData));

HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
© www.soinside.com 2019 - 2024. All rights reserved.