基于HttpClient实现java中实现数据传输及文件传输

1. 在pom文件中引入相关jar

<dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.8</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5</version>
</dependency>

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

2. 创建HttpClientRequestUtil工具类

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpClientRequestUtil {
	private static final HttpClient client = HttpClientBuilder.create().build();

	/**
	* 使用POST请求
	* @author      Calm
	* @param       urlParameters,URL
	* @return
	* @exception
	* @date        2020/8/3 15:33
	*/
	public static String doPost(List<NameValuePair> urlParameters,String URL) {
		String result = "";
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(URL);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
				.setSocketTimeout(3000).setConnectionRequestTimeout(3000)
				.setRedirectsEnabled(true).build();
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(urlParameters, "UTF-8");
			httppost.setEntity(uefEntity);
			httppost.setConfig(requestConfig);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() == 200){
				try {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						result = EntityUtils.toString(entity, "UTF-8");
						System.out.println("--------------------------------------");
						System.out.println("Response content: " +result);
						System.out.println("--------------------------------------");
					}
				} finally {
					response.close();
				}
			}else {
				System.out.println("******************************************请求失败+++++++++++++++++++++++++++++====");
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * GET请求方式
	 * @author      Calm
	 * @param
	 * @return
	 * @exception
	 * @date        2020/7/22 9:26
	 */
	public static String doGet(String URL) {
		try {
			HttpClient client = new DefaultHttpClient();
			//发送get请求
			HttpGet request = new HttpGet(URL);
			HttpResponse response = client.execute(request);
			/**请求发送成功,并得到响应**/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/**读取服务器返回过来的json字符串数据**/
				String strResult = EntityUtils.toString(response.getEntity());

				return strResult;
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	* POST请求application/json
	* @author      Calm
	* @param       jsonStr,URL
	* @return
	* @exception
	* @date        2020/8/3 16:58
	*/
	public static String doPostJson(String jsonStr,String URL) throws  Exception {
		StringEntity sEntity = new StringEntity(JSONObject.fromObject(jsonStr).toString(), "utf-8");
		sEntity.setContentType("application/json");
		HttpPost post = new HttpPost(URL);
		post.setEntity(sEntity);
		HttpResponse response = client.execute(post);
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, "UTF-8");
	}

	/**
	* POST请求发送MultipartFile文件参数
	* @author      Calm
	* @param       
	* @return      
	* @exception   
	* @date        2020/8/13 17:10
	*/
	public static Map<String, String> doPostFile(String url, List<MultipartFile> multipartFiles,String fileParName,
													   Map<String, Object> params, int timeout) {
		Map<String, String> resultMap = new HashMap<String, String>();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			String fileName = null;
			MultipartFile multipartFile = null;
			for (int i = 0; i < multipartFiles.size(); i++) {
				multipartFile = multipartFiles.get(i);
				fileName = multipartFile.getOriginalFilename();
				builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
			}
			//决中文乱码
			ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				if(entry.getValue() == null)
					continue;
				// 类似浏览器表单提交,对应input的name和value
				builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
			}
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交

			// 设置连接超时时间
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
					.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
			httpPost.setConfig(requestConfig);

			HttpEntity responseEntity = response.getEntity();
			resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
			resultMap.put("data", "");
			if (responseEntity != null) {
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
				resultMap.put("data", result);
			}
		} catch (Exception e) {
			resultMap.put("scode", "error");
			resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());

			Writer w = new StringWriter();
			e.printStackTrace(new PrintWriter(w));
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultMap;
	}

}

3. 业务实现类调用Demo

public String uploadFilesToYB(List<MultipartFile> multipartFiles) {
        String ticket = this.getRedisTicket();
        String postUrl = YBZLURL+"/file/upload_file";
        Map<String ,Object> map=new HashMap<>();
        map.put("system_id", YBZLSYSID);
        map.put("ticket", ticket);
        Map<String, String> resultDataMap = HttpClientRequestUtil.doPostFile(postUrl,multipartFiles,"files",map,-1);
        String jsonStr = resultDataMap.get("data");
        if (StringUtils.isNotEmpty(jsonStr)){
            ResultJson js = (ResultJson)FastJsonTools.jsonStringToBean(jsonStr,ResultJson.class);
            if (js.getCode()==200){
                Map<String,String> rsMap = FastJsonTools.jsonStringToMap(js.getInfo());
                String ordersJson = JSONObject.toJSONString(rsMap.get("file_list"));
                return ordersJson;
            }
        }
        return jsonStr;
    }
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答:使用Apache HttpClient可以实现这一目标。首先,你需要创建一个HttpClient实例,并配置它以支持大量数据传输。然后,使用HttpClient的execute方法,创建一个HttpPost对象,并将要传输的数据设置到HttpPost对象,最后调用HttpClient的execute方法,发出HTTP请求,实现数据的传输。 ### 回答2: 在Java,可以使用Apache HttpClient库来进行HTTP请求和响应的操作。下面是使用Java接口httpclient传输大量数据的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.*; import java.util.ArrayList; import java.util.List; public class HttpClientExample { public static void main(String[] args) { String url = "http://example.com/post"; List<String> data = getData(); // 假设data为大量数据的集合 try { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(data)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } client.getConnectionManager().shutdown(); } catch (IOException e) { e.printStackTrace(); } } private static List<String> getData() { List<String> data = new ArrayList<>(); // 添加大量数据到data return data; } } ``` 上述代码使用ApacheHttpClient库创建了一个HttpClient实例,并通过HttpPost方法发送POST请求到指定的URL。使用`setEntity()`方法将数据添加到POST请求。在本例,使用`new UrlEncodedFormEntity(data)`将数据以表单编码的方式添加到请求。如果数据是JSON格式的,可以使用`new StringEntity(data, ContentType.APPLICATION_JSON)`将数据作为JSON字符串添加到请求。 执行POST请求后,通过获取响应的实体`HttpResponse.getEntity()`,可以得到服务器返回的数据。在本例,使用`getContent()`方法获取输入流,并通过BufferedReader以行的形式读取返回的数据。 最后,最好在使用完HttpClient之后调用`client.getConnectionManager().shutdown()`方法释放相关的资源。 需要注意的是,传输大量数据时可能会遇到一些问题,例如超时、内存不足等。可以根据实际情况调整HttpClient的参数和配置,以确保传输过程的稳定性和性能。 ### 回答3: 在Java使用HttpClient传输大量数据可以按照以下步骤进行: 1. 引入HttpClient库:首先,在Java工程引入HttpClient库。可以通过在pom.xml文件添加相应的依赖项来导入。 2. 创建HttpClient对象:使用HttpClientBuilder类创建一个HttpClient对象,该对象将用于发送HTTP请求。 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost请求:创建一个HttpPost请求对象,并设置请求的URL和其他头部信息。如果有需要,还可以设置代理、身份验证、连接超时等。 ```java HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(jsonData)); ``` 4. 设置请求体:如果需要发送大量数据,可以将数据作为请求体传递。可以使用StringEntity、FileEntity等类来设置请求体。 ```java httpPost.setEntity(new StringEntity(data, ContentType.TEXT_PLAIN)); ``` 5. 发送请求并获取响应:通过执行HttpPost请求对象发送请求,并获取响应对象。可以使用CloseableHttpResponse类来接收响应。 ```java CloseableHttpResponse response = httpClient.execute(httpPost); ``` 6. 解析响应:从响应对象获取相应的数据,可以通过EntityUtils类将响应体转换为字符串。 ```java HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); ``` 7. 关闭连接:使用完毕后,需要关闭连接和释放资源。 ```java response.close(); httpClient.close(); ``` 以上是使用HttpClient传输大量数据的基本步骤。根据实际需求,可能还需要处理异常、设置重试机制、添加请求头等其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值