如何在Java中使用HttpPost发送空的二进制数据

huangapple go评论75阅读模式
英文:

how to send empty binary data by HttpPost using java

问题

以下是翻译好的部分:

I wanna implement the HTTP post from curl.
我想要实现来自curl的HTTP POST请求。

The curl command above sends empty binary data.
上面的curl命令发送空的二进制数据。

I know how to send string data.
我知道如何发送字符串数据。

Sending string data
发送字符串数据

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 () {
    }
}

But how to send empty binary data?
但如何发送空的二进制数据?

Trying
尝试

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

It is not work.
这并不起作用。

I read some articles which are not properly solutions.
我阅读了一些不太正确的解决方案的文章。

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

how-to-get-raw-binary-data-from-a-post-request-processed-by-spring

uploading-binary-data-with-httppost

httpclient-post-http-request

There are many similar related articles, but I didn't find the solution. Can anyone give me the code sample for this? Thank you.
有许多类似的相关文章,但我没有找到解决方案。是否有人可以为我提供这方面的代码示例?谢谢。

英文:

I wanna implement the HTTP post from curl.

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

The curl command above sends empty binary data.

I know how to send string data.

Sending string data

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 () {
}

But how to send empty binary data?

Trying

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

It is not work.

I read some articles which are not properly solutions.

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

how-to-get-raw-binary-data-from-a-post-request-processed-by-spring

uploading-binary-data-with-httppost

httpclient-post-http-request

There are many similar related articles, but I didn't find the solution. Can anyone give me the code sample for this? Thank you.

答案1

得分: 2

你提供的代码用于 JSON 类型,而不是二进制类型:

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");

并使用一个空的输入流来初始化实体:

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";
    
    // 创建 HttpClient 实例
    HttpClient httpClient = HttpClientBuilder.create().build();
    
    // 创建带有 URL 的 HttpPost 实例
    HttpPost httpPost = new HttpPost(url);
    
    // 创建带有二进制内容类型的空 HttpEntity
    HttpEntity entity = new InputStreamEntity(IOUtils.toInputStream(""), ContentType.APPLICATION_OCTET_STREAM);
    
    // 将实体设置到请求中
    httpPost.setEntity(entity);
    
    // 发送请求
    httpClient.execute(httpPost);
}
英文:

The code you provide is for json type, not binary type:

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

If you want an empty json request body, do:

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

This the equivalent of

 --data-binary {}

"application/octet-stream" is a generic binary data type, meaning it can be used to represent any type of binary data. This MIME type is commonly used when the content type of the data is unknown or when the data being transferred does not fit any other specific MIME type. It is often used to transfer files or raw binary data.

For binary, use:

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

and initialize the entity with an empty 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);
}

答案2

得分: 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);
英文:
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);

huangapple
  • 本文由 发表于 2023年2月24日 13:39:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定