`

HttpClient4.5 简单入门实例(一)

阅读更多

一、所需要的jar包

   httpclient-4.5.jar

   httpcore-4.4.1.jar

   httpmime-4.5.jar

二、实例

package cn.tzz.apache.httpclient;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpClientUtil {
	private RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(15000)
            .setConnectTimeout(15000)
            .setConnectionRequestTimeout(15000)
            .build();
	
	private static HttpClientUtil instance = null;
	private HttpClientUtil(){}
	public static HttpClientUtil getInstance(){
		if (instance == null) {
			instance = new HttpClientUtil();
		}
		return instance;
	}
	
	/**
	 * 发送 post请求
	 * @param httpUrl 地址
	 */
	public String sendHttpPost(String httpUrl) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
		return sendHttpPost(httpPost);
	}
	
	/**
	 * 发送 post请求
	 * @param httpUrl 地址
	 * @param params 参数(格式:key1=value1&key2=value2)
	 */
	public String sendHttpPost(String httpUrl, String params) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
		try {
			//设置参数
			StringEntity stringEntity = new StringEntity(params, "UTF-8");
			stringEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(stringEntity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sendHttpPost(httpPost);
	}
	
	/**
	 * 发送 post请求
	 * @param httpUrl 地址
	 * @param maps 参数
	 */
	public String sendHttpPost(String httpUrl, Map<String, String> maps) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
		// 创建参数队列  
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (String key : maps.keySet()) {
			nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sendHttpPost(httpPost);
	}
	
	
	/**
	 * 发送 post请求(带文件)
	 * @param httpUrl 地址
	 * @param maps 参数
	 * @param fileLists 附件
	 */
	public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
		MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
		for (String key : maps.keySet()) {
			meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
		}
		for(File file : fileLists) {
			FileBody fileBody = new FileBody(file);
			meBuilder.addPart("files", fileBody);
		}
		HttpEntity reqEntity = meBuilder.build();
		httpPost.setEntity(reqEntity);
		return sendHttpPost(httpPost);
	}
	
	/**
	 * 发送Post请求
	 * @param httpPost
	 * @return
	 */
	private String sendHttpPost(HttpPost httpPost) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			httpPost.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpPost);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	/**
	 * 发送 get请求
	 * @param httpUrl
	 */
	public String sendHttpGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return sendHttpGet(httpGet);
	}
	
	/**
	 * 发送 get请求Https
	 * @param httpUrl
	 */
	public String sendHttpsGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return sendHttpsGet(httpGet);
	}
	
	/**
	 * 发送Get请求
	 * @param httpPost
	 * @return
	 */
	private String sendHttpGet(HttpGet httpGet) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}
	
	/**
	 * 发送Get请求Https
	 * @param httpPost
	 * @return
	 */
	private String sendHttpsGet(HttpGet httpGet) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
			httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
			httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseContent;
	}
}

 三、测试代码

package cn.tzz.apache.httpclient;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

public class HttpClientUtilTest {
	
	@Test
	public void testSendHttpPost1() {
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpPost("http://localhost:8089/test/send?username=test01&password=123456");
		System.out.println("reponse content:" + responseContent);
	}
	
	@Test
	public void testSendHttpPost2() {
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpPost("http://localhost:8089/test/send", "username=test01&password=123456");
		System.out.println("reponse content:" + responseContent);
	}
	
	@Test
	public void testSendHttpPost3() {
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("username", "test01");
		maps.put("password", "123456");
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpPost("http://localhost:8089/test/send", maps);
		System.out.println("reponse content:" + responseContent);
	}
	@Test
	public void testSendHttpPost4() {
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("username", "test01");
		maps.put("password", "123456");
		List<File> fileLists = new ArrayList<File>();
		fileLists.add(new File("D://test//httpclient//1.png"));
		fileLists.add(new File("D://test//httpclient//1.txt"));
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpPost("http://localhost:8089/test/sendpost/file", maps, fileLists);
		System.out.println("reponse content:" + responseContent);
	}

	@Test
	public void testSendHttpGet() {
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpGet("http://localhost:8089/test/send?username=test01&password=123456");
		System.out.println("reponse content:" + responseContent);
	}
	
	@Test
	public void testSendHttpsGet() {
		String responseContent = HttpClientUtil.getInstance()
				.sendHttpsGet("https://www.baidu.com");
		System.out.println("reponse content:" + responseContent);
	}

}

 

@RequestMapping(value = "/test/send")
	@ResponseBody
	public Map<String, String> sendPost(HttpServletRequest request) {
		Map<String, String> maps = new HashMap<String, String>();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		maps.put("username", username);
		maps.put("password", password);
		return maps;
	}
	
	@RequestMapping(value = "/test/sendpost/file",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> sendPostFile(@RequestParam("files") MultipartFile [] files,HttpServletRequest request) {
		Map<String, String> maps = new HashMap<String, String>();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		maps.put("username", username);
		maps.put("password", password);
		
		try {
			for(MultipartFile file : files){
				String fileName = file.getOriginalFilename();
				fileName = new String(fileName.getBytes(),"UTF-8");
				InputStream is = file.getInputStream();
				if (fileName != null && !("".equals(fileName))) {
					File directory = new File("D://test//httpclient//file");
					if (!directory.exists()) {
						directory.mkdirs();
					}
					String filePath = ("D://test//httpclient//file") + File.separator + fileName;
					FileOutputStream fos = new FileOutputStream(filePath);
					byte[] buffer = new byte[1024];
					while (is.read(buffer) > 0) {
						fos.write(buffer, 0, buffer.length);
					}
					fos.flush();
					fos.close();
					maps.put("file--"+fileName, "uploadSuccess");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return maps;
	}

 

分享到:
评论
6 楼 Jackney 2017-08-31  
5 楼 hhzhaoheng 2017-06-06  
赞一个
4 楼 lihongda 2017-04-12  
麻烦问一下,上传文件如何从页面获取文件真实路径。要不实现不了上传啊
3 楼 lairunlin 2017-04-06  
点个赞,多谢。
2 楼 janson56 2017-03-09  

    :idea: 
1 楼 dhpwater 2015-12-10  
<img>alert()</img>

相关推荐

    httpclient4.5 jar包

    - **创建HttpClient实例**:通过`HttpClientBuilder`构建器可以定制化配置HttpClient实例,如设置连接超时、重试策略等。 - **发起HTTP请求**:使用`HttpGet`, `HttpPost`等请求方法,结合`URI`或`URL`指定请求...

    httpclient4.5.zip

    在使用HttpClient 4.5时,开发者需要了解如何创建HttpClient实例,设置请求参数,发送请求并解析响应。例如,你可以创建一个`CloseableHttpClient`对象,然后使用`HttpGet`或`HttpPost`构造请求,添加请求头和参数,...

    HttpClient4.5 Jar包

    在使用HttpClient 4.5时,可以通过"使用说明.txt"文件获取详细的配置和使用指南,了解如何导入httpclient-4.5所需jar包,以及如何创建和配置HttpClient实例,进行GET、POST等请求,处理响应,管理连接和会话,以及...

    HttpClient4.5 实现https忽略SSL证书验证

    使用HttpClient4.5实现https请求忽略SSL证书验证工具类

    HttpClient4.5全部jar包+简单实例

    这个压缩包包含了HttpClient 4.5所需的全部jar包,以及一个简单的实例`PTXCheckTools.java`,方便用户快速理解和应用。 HttpClient库的核心功能包括: 1. **HTTP协议支持**:HttpClient支持HTTP/1.1和HTTP/2协议,...

    httpclient4.5 绕过ssl认证文件访问

    HTTPClient 4.5中提供了这样的功能,可以让我们自定义SSL上下文,从而绕过默认的证书验证。以下是如何操作的步骤: 1. **创建自定义的X509TrustManager**:这个类负责验证服务器证书。我们可以创建一个信任所有证书...

    HttpClient4.5 CHM 最新版

    HttpClient4.5 CHM 最新版 与Apache官方一致

    HttpClient4.5

    HttpClient4.5需要的jar包HttpClient4.5需要的jar包HttpClient4.5需要的jar包HttpClient4.5需要的jar包

    httpclient-4.5所需jar包

    1. **创建HttpClient实例**:首先,需要通过`HttpClientBuilder`构建一个HttpClient实例,设置连接池大小、超时时间等参数。 2. **构建HttpGet/HttpPost请求**:使用`HttpGet`或`HttpPost`类创建HTTP请求,设置URL...

    httpclient 4.5 api文档

    ### httpclient 4.5 API文档知识点概览 #### 一、基础知识 ##### 1.1 请求执行 **1.1.1 HTTP请求** - **定义**:HTTP客户端通过发送HTTP请求来与服务器进行交互。 - **组成**: - 方法(GET、POST等); - URI...

    httpclient4.5源码学习

    HttpClient 4.5 版本作为其重要的一个迭代,引入了许多新特性和优化,使得其在性能、稳定性和易用性上都有显著提升。本文将深入探讨 HttpClient 4.5 的源码,以帮助开发者更好地理解和使用这一工具。 一、...

    httpclient4.5的JAR包

    1. **创建HttpClient实例**:首先,我们需要创建一个HttpClient对象,这通常通过HttpClientBuilder或HttpAsyncClientBuilder构建。例如: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); `...

    httpclient4.5.jar

    httpclient4.5.jar开发架包,包含所需要依赖的架包 。

    httpclient4.5工具包

    《HttpClient 4.5工具包详解》 HttpClient是一款强大的HTTP客户端工具包,广泛应用于Java开发中,用于执行HTTP和HTTPS请求。HttpClient 4.5版本是其一个重要的更新,提供了许多增强的功能和优化,旨在更好地支持...

    httpClient4.5所需工具包

    在标题“httpClient4.5所需工具包”中,"HttpClient4.5"指的是这个项目的第4.5版本,这是一个重要的升级,包含了许多改进和新特性,以提高性能和稳定性。 HttpClient 4.5主要知识点包括: 1. **连接管理**:...

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    HttpClient 4.5 封装的工具类 HttpUtil 可用于爬虫和模拟登陆

    基于Apache HttpClient 4.5.2 封装的工具类 HttpUtil 可... &lt;artifactId&gt;httpclient &lt;version&gt;4.5.2 &lt;groupId&gt;org.apache.httpcomponents &lt;artifactId&gt;httpmime&lt;/artifactId&gt; &lt;version&gt;4.5.1 &lt;/dependency&gt;

    HttpClient4.5-API-部分翻译

    由网上博客整理而成的PDF。该PDF是关于HttpClient4.5-API进行部分翻译,我觉得翻译的很不错,就整理下来留存一份。原博客地址:http://blog.csdn.net/u011179993/article/details/47123727 侵删。谢谢。

    httpclient jar 包 4.5

    在标题“httpclient jar 包 4.5”中提到的,是HttpClient的一个特定版本——4.5。这个版本不仅包含了HttpClient的核心功能,还可能包含了其他相关组件,以提供一个完整的HTTP客户端解决方案。描述中提到的“包含所有...

Global site tag (gtag.js) - Google Analytics