使用HttpClient上传文件怎么设置请求头

当我们后端使用Httpclient往目标接口发文件的时候往往要设置请求头,不然会出现对方没有接受到文件的错误提示。

// 创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://localhost:8000/api/v1/upload");
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000) // 设置连接超时为15秒
                .setSocketTimeout(15000)  // 设置读取超时为15秒
                .build();
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        String filehash = null;
        try {
            //添加文件部分
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//解决文件名乱码问题
            builder.setCharset(Charset.forName("UTF-8"));
            builder.addTextBody("X-Mobsf-Api-Key", "6cd667ef221e143acfd76fa0e892e4f026d6bf3f119e35a9bb013a278f931e35", ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            builder.addPart("file", new FileBody(file));
            // 构建请求体
            httpPost.setEntity(builder.build());

            // 设置请求头
            httpPost.setHeader("Content-Type", "multipart/form-data; boundary=XnwR6DgMazZmZ4a7w5dt_wrCvcjupAetcV8Ccx; charset=UTF-8");
            httpPost.setHeader(httpPost.getEntity().getContentType());
            httpPost.setHeader("Authorization", "6cd667ef221e143acfd76fa0e892e4f026d6bf3f119e35a9bb013a278f931e35");


            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=XnwR6DgMazZmZ4a7w5dt_wrCvcjupAetcV8Ccx; charset=UTF-8");
httpPost.setHeader(httpPost.getEntity().getContentType());这俩行代码可以不用,在源码中已经设置了请求头。
builder.addPart("file", new FileBody(file));在这段代码中我们ctrl跟进看看
public MultipartEntityBuilder addPart(String name, ContentBody contentBody) {
        Args.notNull(name, "Name");
        Args.notNull(contentBody, "Content body");
        return this.addPart(FormBodyPartBuilder.create(name, contentBody).build());
    }

这里是把传进来的文件名和文件构建FormBodyPart对象

public MultipartEntityBuilder addPart(FormBodyPart bodyPart) {
        if (bodyPart == null) {
            return this;
        } else {
            if (this.bodyParts == null) {
                this.bodyParts = new ArrayList();
            }

            this.bodyParts.add(bodyPart);
            return this;
        }
    }

public class FormBodyPart {
    private final String name;
    private final Header header;
    private final ContentBody body;

    FormBodyPart(String name, ContentBody body, Header header) {
        Args.notNull(name, "Name");
        Args.notNull(body, "Body");
        this.name = name;
        this.body = body;
        this.header = header != null ? header : new Header();
    }

    /** @deprecated */
    @Deprecated
    public FormBodyPart(String name, ContentBody body) {
        Args.notNull(name, "Name");
        Args.notNull(body, "Body");
        this.name = name;
        this.body = body;
        this.header = new Header();
        this.generateContentDisp(body);
        this.generateContentType(body);
        this.generateTransferEncoding(body);
    }

    public String getName() {
        return this.name;
    }

    public ContentBody getBody() {
        return this.body;
    }

    public Header getHeader() {
        return this.header;
    }

    public void addField(String name, String value) {
        Args.notNull(name, "Field name");
        this.header.addField(new MinimalField(name, value));
    }

    /** @deprecated */
    @Deprecated
    protected void generateContentDisp(ContentBody body) {
        StringBuilder buffer = new StringBuilder();
        buffer.append("form-data; name=\"");
        buffer.append(this.getName());
        buffer.append("\"");
        if (body.getFilename() != null) {
            buffer.append("; filename=\"");
            buffer.append(body.getFilename());
            buffer.append("\"");
        }

        this.addField("Content-Disposition", buffer.toString());
    }

    /** @deprecated */
    @Deprecated
    protected void generateContentType(ContentBody body) {
        ContentType contentType;
        if (body instanceof AbstractContentBody) {
            contentType = ((AbstractContentBody)body).getContentType();
        } else {
            contentType = null;
        }

        if (contentType != null) {
            this.addField("Content-Type", contentType.toString());
        } else {
            StringBuilder buffer = new StringBuilder();
            buffer.append(body.getMimeType());
            if (body.getCharset() != null) {
                buffer.append("; charset=");
                buffer.append(body.getCharset());
            }

            this.addField("Content-Type", buffer.toString());
        }

    }

    /** @deprecated */
    @Deprecated
    protected void generateTransferEncoding(ContentBody body) {
        this.addField("Content-Transfer-Encoding", body.getTransferEncoding());
    }
}
可以发现在FormBodyPart的构建方法中已经添加了请求头。如果没有你想设置的请求头可以自己添加。
以下是使用HttpClient上传文件的示例代码: ``` import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class FileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.txt"; // 创建HttpClient CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost(url); // 创建multipart/form-data实体 File file = new File(filePath); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()) .build(); // 设置请求实体 httpPost.setEntity(httpEntity); try { // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 输出响应结果 System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getEntity().getContent().toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭HttpClient try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 在上面的示例代码中,我们使用了Apache HttpClient 4.x库来发送POST请求,并上传文件。我们首先创建了一个CloseableHttpClient实例,然后创建一个HttpPost实例,并设置请求实体为multipart/form-data类型的实体。 在实体中,我们添加了一个二进制文件体,它将文件添加到请求中。在这个例子中,我们使用了File类来表示文件,并用ContentType.DEFAULT_BINARY创建了一个ContentType实例。 最后,我们执行请求,并输出响应结果。注意,在使用HttpClient时,我们需要手动关闭HttpClient实例,以释放连接和资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值