HttpClient-- 模拟表单上传文件

Posted 听歌敲代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient-- 模拟表单上传文件相关的知识,希望对你有一定的参考价值。

1.maven依赖

      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.2</version>
    </dependency>

2.代码实现

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.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientUpload {

    public static void main(String[] args) {
        // 将 fileUrl 上传到 url中,上传成功后,返回 下载地址
        String url = "http://127.0.0.1:8080/Joe/upload";
        String fileUrl = "C:/abc.txt";
        try {
            System.out.println(post(url, "file", new File(fileUrl)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * post:(上传).
     * 
     * @author Joe Date:2017年9月11日下午5:37:46
     * @param serverUrl
     * @param fileParamName
     * @param file
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String serverUrl, String fileParamName, File file)
            throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(serverUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 上传的文件
        builder.addBinaryBody(fileParamName, file);
        HttpEntity httpEntity = builder.build();
        httpPost.setEntity(httpEntity);
        // 请求获取数据的超时时间 、 设置从connect
        // Manager获取Connection超时时间(因为目前版本是可以共享连接池的)、设置连接超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000).setConnectionRequestTimeout(3000)
                .setConnectTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity());
    }
}

 

以上是关于HttpClient-- 模拟表单上传文件的主要内容,如果未能解决你的问题,请参考以下文章

android的自带的httpClient 怎么上传文件

使用 HttpClient 上传多部分表单文件

java模拟http请求上传文件,基于Apache的httpclient

HTTPclient使用MultipartEntity怎么上传文件

如何在 Python 中模拟 post 表单来上传文件

httpclient模拟post请求json封装表单数据