大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要讲解了Java http请求封装工具类的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
专注于为中小企业提供做网站、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业寻甸免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了数千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现。
本文用httpclient去实现,需要导入httpclient和httpcore两个jar包,测试时用的httpclient-4.5.1和httpcore-4.4.3。
HttpMethod.java
package demo; public enum HttpMethod { GET, POST; }
HttpHeader.java
package demo; import java.util.HashMap; import java.util.Map; /** * 请求头 */ public class HttpHeader { private Mapparams = new HashMap (); public HttpHeader addParam(String name, String value) { this.params.put(name, value); return this; } public Map getParams() { return this.params; } }
HttpParamers.java
package demo; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.alibaba.fastjson.JSON; /** * 请求参数 */ public class HttpParamers { private Mapparams = new HashMap (); private HttpMethod httpMethod; private String jsonParamer = ""; public HttpParamers(HttpMethod httpMethod) { this.httpMethod = httpMethod; } public static HttpParamers httpPostParamers() { return new HttpParamers(HttpMethod.POST); } public static HttpParamers httpGetParamers() { return new HttpParamers(HttpMethod.GET); } public HttpParamers addParam(String name, String value) { this.params.put(name, value); return this; } public HttpMethod getHttpMethod() { return this.httpMethod; } public String getQueryString(String charset) throws IOException { if ((this.params == null) || (this.params.isEmpty())) { return null; } StringBuilder query = new StringBuilder(); Set > entries = this.params.entrySet(); for (Map.Entry entry : entries) { String name = entry.getKey(); String value = entry.getValue(); query.append("&").append(name).append("=").append(URLEncoder.encode(value, charset)); } return query.substring(1); } public boolean isJson() { return !isEmpty(this.jsonParamer); } public Map getParams() { return this.params; } public String toString() { return "HttpParamers " + JSON.toJSONString(this); } public String getJsonParamer() { return this.jsonParamer; } public void setJsonParamer() { this.jsonParamer = JSON.toJSONString(this.params); } private static boolean isEmpty(CharSequence cs) { return (cs == null) || (cs.length() == 0); } }
HttpClient.java
package demo; import java.io.IOException; import java.util.Map; import java.util.Set; import org.apache.http.HttpEntity; 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.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; public class HttpClient { public static final String DEFAULT_CHARSET = "UTF-8"; public static final String JSON_CONTENT_FORM = "application/json;charset=UTF-8"; public static final String CONTENT_FORM = "application/x-www-form-urlencoded;charset=UTF-8"; public static String doService(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws Exception { HttpMethod httpMethod = paramers.getHttpMethod(); switch (httpMethod) { case GET: return doGet(url, paramers, header, connectTimeout, readTimeout); case POST: return doPost(url, paramers, header, connectTimeout, readTimeout); } return null; } /** * post方法 * @param url * @param paramers * @param header * @param connectTimeout * @param readTimeout * @return * @throws IOException */ public static String doPost(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws IOException { String responseData = ""; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try{ String query = null; HttpPost httpPost = new HttpPost(url); setHeader(httpPost, header); if (paramers.isJson()) { //json数据 httpPost.setHeader(HTTP.CONTENT_TYPE, JSON_CONTENT_FORM); query = paramers.getJsonParamer(); } else { //表单数据 httpPost.setHeader(HTTP.CONTENT_TYPE, CONTENT_FORM); query = paramers.getQueryString(DEFAULT_CHARSET); } if(query != null){ HttpEntity reqEntity = new StringEntity(query); httpPost.setEntity(reqEntity); } httpClient = HttpClients.createDefault(); httpResponse = httpClient.execute(httpPost); HttpEntity resEntity = httpResponse.getEntity(); responseData = EntityUtils.toString(resEntity); } catch (Exception e){ e.printStackTrace(); } finally{ httpResponse.close(); httpClient.close(); } return responseData; } /** * get方法 * @param url * @param params * @param header * @param connectTimeout * @param readTimeout * @return * @throws IOException */ public static String doGet(String url, HttpParamers params, HttpHeader header, int connectTimeout, int readTimeout) throws IOException { String responseData = ""; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try{ String query = params.getQueryString(DEFAULT_CHARSET); url = buildGetUrl(url, query); HttpGet httpGet = new HttpGet(url); setHeader(httpGet, header); httpClient = HttpClients.createDefault(); httpResponse = httpClient.execute(httpGet); HttpEntity resEntity = httpResponse.getEntity(); responseData = EntityUtils.toString(resEntity); } catch (Exception e){ e.printStackTrace(); } finally{ httpResponse.close(); httpClient.close(); } return responseData; } private static void setHeader(HttpRequestBase httpRequestBase, HttpHeader header){ if(header != null){ MapheaderMap = header.getParams(); if (headerMap != null && !headerMap.isEmpty()) { Set > entries = headerMap.entrySet(); for (Map.Entry entry : entries) { String name = entry.getKey(); String value = entry.getValue(); httpRequestBase.setHeader(name, value); } } } } private static String buildGetUrl(String url, String query) throws IOException { if (query == null || query.equals("")) { return url; } StringBuilder newUrl = new StringBuilder(url); boolean hasQuery = url.contains("?"); boolean hasPrepend = (url.endsWith("?")) || (url.endsWith("&")); if (!hasPrepend) { if (hasQuery) { newUrl.append("&"); } else { newUrl.append("?"); hasQuery = true; } } newUrl.append(query); hasPrepend = false; return newUrl.toString(); } }
HttpService.java
package demo; import java.util.Map; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; public class HttpService { private String serverUrl; private int connectTimeout = 15000; private int readTimeout = 30000; public HttpService(String serverUrl) { this.serverUrl = serverUrl.trim(); } public MapcommonService(String serviceUrl, HttpParamers paramers) throws Exception{ return commonService(serviceUrl, paramers, null); } public Map commonService(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception{ String response = service(serviceUrl, paramers, header); try { Map result = JSONObject.parseObject(response, new TypeReference
测试例子Test1.java
package demo; import org.junit.Ignore; import org.junit.Test; public class Test1 { //免费的在线REST服务, 提供测试用的HTTP请求假数据 //接口信息说明可见:http://www.hangge.com/blog/cache/detail_2020.html String uri = "http://jsonplaceholder.typicode.com"; //get方式请求数据 //请求地址:http://jsonplaceholder.typicode.com/posts @Ignore("暂时忽略") @Test public void test1() { System.out.print("\n" + "test1---------------------------"+ "\n"); HttpParamers paramers = HttpParamers.httpGetParamers(); String response = ""; try { HttpService httpService = new HttpService(uri); response = httpService.service("/posts", paramers); } catch (Exception e) { e.printStackTrace(); } System.out.print(response); } //get方式请求数据 //请求地址:http://jsonplaceholder.typicode.com/posts?userId=5 @Ignore("暂时忽略") @Test public void test2() { System.out.print("\n" + "test2---------------------------"+ "\n"); HttpParamers paramers = HttpParamers.httpGetParamers(); paramers.addParam("userId", "5"); String response = ""; try { HttpService httpService = new HttpService(uri); response = httpService.service("/posts", paramers); } catch (Exception e) { e.printStackTrace(); } System.out.print(response); } //post方式请求数据 //请求地址:http://jsonplaceholder.typicode.com/posts @Test public void test3() { System.out.print("\n" + "test3---------------------------"+ "\n"); HttpParamers paramers = HttpParamers.httpPostParamers(); paramers.addParam("time", String.valueOf(System.currentTimeMillis())); String response = ""; try { HttpService httpService = new HttpService(uri); response = httpService.service("/posts", paramers); } catch (Exception e) { e.printStackTrace(); } System.out.print(response); } }
看完上述内容,是不是对Java http请求封装工具类的方法有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。