背景
虽然有了dubbo提供的服务接口,但是在项目与项目之间仍旧存在着http访问的接口。那么怎么调用呢?httpClient这个工具包用起来就十分的方便了。一般获取到接口返回的数据时,都需要做json反序列化为对象。可以使用spring-mvc依赖的 com.fasterxml.jackson.core。也可以使用com.alibaba.fastjson
参考资料:
https://www.cnblogs.com/sharpest/p/6406013.html
https://blog.csdn.net/xiaoxian8023/article/details/49865335
https://blog.csdn.net/xiaoxian8023/article/details/49619777
引用jar包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency>
json的jar包,选择其中一个就可以
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency>
http进行访问的基本步骤
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。一般都使用连接池来创建
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。一般HttpClient是从http连接池里获取。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接。
代码篇
连接池对象
import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import javax.annotation.PostConstruct; import javax.net.ssl.SSLContext; /** * @author WGP * @description 连接池管理对象 * @date 2018/5/6 **/ public class HttpConnectionManager { PoolingHttpClientConnectionManager cm = null; @PostConstruct public void init(){ LayeredConnectionSocketFactory sslsf = null; try{ sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault()); }catch (Exception e){ e.printStackTrace(); } Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https",sslsf) .register("http",new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); } public CloseableHttpClient getHttpClient(){ CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); return httpClient; } }
基本使用的方法
public class HttpClient { public void postJson() throws Exception { String url = "http:/localhost/shop"; //1、创建http连接 CloseableHttpClient httpClient = new HttpConnectionManager().getHttpClient(); CloseableHttpResponse response = null; try { //2、创建请求对象 HttpPost httpPost = new HttpPost(url); // 3、设置请求头及数据 httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); String json = "{'ids':['html1','html2'}"; StringEntity se = new StringEntity(json); se.setContentEncoding("UTF-8"); httpPost.setEntity(se); //4、访问http接口 response = httpClient.execute(httpPost); if(response != null && response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); if (entity != null) { String res = EntityUtils.toString(entity, "UTF-8"); //5、下面可以对res做json反序列化处理 } } } catch (Exception e) { throw e; } finally { closeHttp(httpClient,response); } } public void postForm() throws Exception { CloseableHttpClient httpClient = new HttpConnectionManager().getHttpClient(); CloseableHttpResponse response = null; try { String url = "your/path"; HttpPost httpPost = new HttpPost(url); List<NameValuePair> formParams = new ArrayList<>(8); formParams.add(new BasicNameValuePair("username", "yourname")); formParams.add(new BasicNameValuePair("password", "pass")); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(uefEntity); response = httpClient.execute(httpPost); if(response != null && response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); if (entity != null) { String res = EntityUtils.toString(entity, "UTF-8"); //下面可以对res做json反序列化处理 } } } catch (Exception e) { throw e; } finally { closeHttp(httpClient, response); } } public void getRequest() throws Exception { CloseableHttpClient httpClient = new HttpConnectionManager().getHttpClient(); CloseableHttpResponse response = null; try { String url = "your/get/path"; HttpGet httpGet = new HttpGet(url); response = httpClient.execute(httpGet); if(response != null && response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); if (entity != null) { String res = EntityUtils.toString(entity, "UTF-8"); //下面可以对res做json反序列化处理 } } } catch (Exception e) { throw e; } finally { closeHttp(httpClient, response); } } private void closeHttp(CloseableHttpClient httpClient, CloseableHttpResponse response) throws IOException { try { if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException ex) { throw ex; } } }