HttpClient 使用 Post 方法传输文件

HttpClient 使用 Post 方法传输文件

一、依赖

httpmime-4.5.13.jar
httpcore-4.4.15.jar
httpclient-4.5.13.jar
fastjson-1.2.15.jar
commons-logging-1.1.1.jar
commons-codec-1.15.jar

二、代码

package com;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 网络请求类
 * @author wxhntmy
 */
public class RestMock<K, V> {

	private static SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	
	/**
	 * http post请求,带头信息和传文件
	 *
	 * @param urlStr        http请求的地址
	 * @param APIKey        用户名
	 * @param Authorization 认证密码
	 * @param file          文件
	 * @return 响应信息
	 */
	public static String doPost(String urlStr, String APIKey, String Authorization, File file) {

		System.out.println("url----------------> " + urlStr);

		String sResponse = "{}";

		Date statTime = new Date();
		System.out.println("----------请求开始时间:" + simpleFormat.format(statTime));
		try {
			// 提取到文件名
			String fileName = file.getName();
			FileInputStream fileInputStream = null;
			InputStream is = null;
			if (null != file) {
				try {
					fileInputStream = new FileInputStream(file);// 与根据File类对象的所代表的实际文件建立链接创建fileInputStream对象
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					System.out.println("------文件不存在或者文件不可读或者文件是目录--------");
				}
				// 转换成文件流
				is = fileInputStream;
			}
			
			// 创建HttpClient
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(urlStr);
			
			//设置超时时间,这个是httpclient 4.3版本之后的设置方法
			RequestConfig requestConfig =  RequestConfig.custom()
					.setSocketTimeout(20000)
					.setConnectTimeout(20000)
					.build();
			httpPost.setConfig(requestConfig);
			
			httpPost.addHeader("APIKey", APIKey);
			httpPost.addHeader("Authorization", Authorization);
			
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			
			/* 绑定文件参数,传入文件流和 contenttype,此处也可以继续添加其他 formdata 参数 */
			builder.addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, fileName);
			
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);

			// 执行提交
			HttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			
			System.out.println("-----------------状态码--------------");
			System.out.println("---------------------->statusCode: "+statusCode);
			
			HttpEntity responseEntity = response.getEntity();
			
			//响应状态码200
			if (statusCode == HttpStatus.SC_OK) {
				if (null != responseEntity) {
					// 将响应的内容转换成字符串
					String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
					sResponse = JSONObject.parse(result).toString();
					System.out.println("sResponse1:--------------->" + sResponse);
				}
			
			}
			//响应状态码不是200
			else {
				if (null != responseEntity) {
					// 将响应的内容转换成字符串
					String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
					sResponse = JSONObject.parse(result).toString();
					System.out.println("sResponse2:--------------->" + sResponse);
				}
			}
			
			Date endTime = new Date();
			System.out.println("----------请求结束时间:" + simpleFormat.format(endTime));
			
			Date totalTime = new Date(endTime.getTime() - statTime.getTime());
			
			System.out.println("----------请求总用时:"  + 
				simpleFormat.format(totalTime).substring(simpleFormat.format(totalTime).lastIndexOf(":") + 1)
				 + " 秒");
			
			if (null != is) {
				is.close();
			}
			if (null != fileInputStream) {
				is.close();
			}
			if (null != httpClient) {
				httpClient.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return sResponse;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菠萝蚊鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值