使用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的构建方法中已经添加了请求头。如果没有你想设置的请求头可以自己添加。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值