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

 

posted @ 2017-09-17 17:25  小葱拌豆腐~  阅读(1808)  评论(0编辑  收藏  举报