背景
本文章是为了快速学习,更深入的了解一些内容而设定,一般地,复制代码即可运行。
Apache HttpClient
HttpClient是Apache Jakarta Common下子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且支持HTTP协议最新的版本和建议。
Java Servlet实现服务器端
参考: Maven创建Web项目,Servlet、JSP,配置Tomcat运行
处理普通GET、POST请求的Servlet
package com.what21.servlet;import com.fasterxml.jackson.databind.ObjectMapper;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.util.*;@WebServlet("/service/general")public class GeneralHttpServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // 接收所有的header参数 Enumeration<String> headerEnumer = request.getHeaderNames(); System.out.println("-------------------------------------------------"); while (headerEnumer.hasMoreElements()) { String name = headerEnumer.nextElement(); System.out.println(name + ":" + request.getHeader(name)); } System.out.println("-------------------------------------------------"); Map<String, String[]> parameterMap = request.getParameterMap(); Set<String> keySet = parameterMap.keySet(); for (String key : keySet) { System.out.println(key + ":" + Arrays.toString(parameterMap.get(key))); } System.out.println("-------------------------------------------------"); Map<String, Object> dataMap = new HashMap<>(); dataMap.put("code", "ok"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(dataMap); response.setContentType("text/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print(json); writer.flush(); }}
处理普通POST JSON请求的Servlet
package com.what21.servlet;import com.fasterxml.jackson.databind.ObjectMapper;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.*;@WebServlet("/service/json")public class PostJsonHttpServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收所有的header参数 Enumeration<String> headerEnumer = request.getHeaderNames(); System.out.println("-------------------------------------------------"); while (headerEnumer.hasMoreElements()) { String name = headerEnumer.nextElement(); System.out.println(name + ":" + request.getHeader(name)); } System.out.println("-------------------------------------------------"); InputStream inputStream = request.getInputStream(); int len = -1; byte buf[] = new byte[512];//缓冲区 ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = inputStream.read(buf)) != -1) { baos.write(buf, 0, len); } String requestJson = new String(baos.toByteArray(), "UTF-8"); ObjectMapper objectMapper = new ObjectMapper(); Map<Object, Object> requestMap = objectMapper.readValue(requestJson, Map.class); System.out.println("requestMap=" + requestMap); System.out.println("-------------------------------------------------"); Map<String, Object> dataMap = new HashMap<>(); dataMap.put("code", "ok"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(dataMap); response.setContentType("text/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print(json); writer.flush(); }}HttpClient4实现客户端调用
pom.xml
<dependencies> <!-- Web Dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- commons.lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency> <!-- 雪花算法 --> <dependency> <groupId>com.relops</groupId> <artifactId>snowflake</artifactId> <version>1.1</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.13.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.13.1</version> </dependency> <!-- HttpClient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1</version> </dependency> <!--测试使用 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- lombok插件--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency></dependencies>
实现的工具类
package com.what21.httpclient4;import org.apache.http.Header;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.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicHeader;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.*;public class HttpClientHelperUtils { /** * @param url * @return */ public static String get(String url) { String result = null; HttpEntity httpEntity = null; try { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建POST HttpGet httpGet = new HttpGet(url); httpGet.setConfig(getRequestConfig()); // 设置头参数 Header header = new BasicHeader("Accept-Encoding", null); httpGet.setHeader(header); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); } catch (IOException e) { e.printStackTrace(); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException e) { // http请求释放资源异常 e.printStackTrace(); } } return result; } /** * @param url * @param paramsMap * @return */ public static String post(String url, Map<String, String> paramsMap) { String result = null; HttpEntity httpEntity = null; try { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建POST HttpPost httpPost = new HttpPost(url); httpPost.setConfig(getRequestConfig()); // 设置头参数 Header header = new BasicHeader("Accept-Encoding", null); httpPost.setHeader(header); // 添加参数 List<NameValuePair> nameValuePairs = new ArrayList<>(); if (paramsMap != null && paramsMap.size() > 0) { Set<String> keySet = paramsMap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = paramsMap.get(key); nameValuePairs.add(new BasicNameValuePair(key, value)); } } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // 执行 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); } catch (IOException e) { e.printStackTrace(); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException e) { // http请求释放资源异常 e.printStackTrace(); } } return result; } /** * @param url * @param json * @return */ public static String postByContentTypeToJson(String url, String json) { String result = null; HttpEntity httpEntity = null; try { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建POST HttpPost httpPost = new HttpPost(url); httpPost.setConfig(getRequestConfig()); // 设置头参数 Header header = new BasicHeader("Accept-Encoding", null); httpPost.setHeader(header); // 头设置报文和通讯格式 StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON); stringEntity.setContentEncoding("UTF-8"); httpPost.setEntity(stringEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); } catch (IOException e) { e.printStackTrace(); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException e) { // http请求释放资源异常 e.printStackTrace(); } } return result; } /** * @return */ public static RequestConfig getRequestConfig() { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(180 * 1000) // 连接超时时间 .setConnectTimeout(180 * 1000) // 请求超时时间 .setConnectionRequestTimeout(180 * 1000) // 连接请求超时时间 .setRedirectsEnabled(true) // 重定向开关 .build(); return requestConfig; }}
工具类的调用案例
package com.what21.httpclient4;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import java.util.HashMap;import java.util.Map;public class HttpClientHelperUtilsDemo { public static void main(String[] args) { // get调用 String getUrl = "http://localhost:9090/web/service/general?id=xfd&name=小奋斗"; String getResult = HttpClientHelperUtils.get(getUrl); System.out.println(getResult); //===================================================================// // post context-type String postUrl = "http://localhost:9090/web/service/general"; Map<String, String> paramsMap = new HashMap<>(); paramsMap.put("id", "xfd"); paramsMap.put("name", "小奋斗"); String postResult = HttpClientHelperUtils.post(postUrl, paramsMap); System.out.println(postResult); //===================================================================// String postUrl2 = "http://localhost:9090/web/service/json"; String json = "{}"; try { Map<String, String> jsonMap = new HashMap<>(); jsonMap.put("id", "xfd"); jsonMap.put("name", "小奋斗"); ObjectMapper mapper = new ObjectMapper(); json = mapper.writeValueAsString(jsonMap); } catch (JsonProcessingException e) { e.printStackTrace(); } String postResultToJson = HttpClientHelperUtils.postByContentTypeToJson(postUrl2, json); System.out.println(postResultToJson); }}