HttpClient 使用 Post 方法传输文件

Posted 菠萝蚊鸭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
	


以上是关于HttpClient 使用 Post 方法传输文件的主要内容,如果未能解决你的问题,请参考以下文章

c# 使用HttpClient的post,get方法传输json

c# 使用HttpClient的post,get方法传输json

HttpClient POST 上传失败,没有文件传输和格式错误的生成内容处置

使用HttpClient和WebRequest时POST一个对象的写法

HttpClient使用post方法提交数据后服务端如何获得这些参数

如何使用HttpClient模拟浏览器GET POST