一:httpUrlConnection
1.获取HttpURLConnection连接对象
/*** 获取HttpURLConnection连接对象* @param url 远程调用的url* @return*/public static HttpURLConnection getHttpURLConnection(String url){try {//建立连接URL httpUrl = new URL(url);HttpURLConnection urlConnection =(HttpURLConnection)httpUrl.openConnection();//向文件所在服务器发送标识信息,模拟浏览器urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");return urlConnection;} catch (IOException e) {e.printStackTrace();return null;}}
2.远程调用代码
/*** 远程调用登录接口*/public void accessLoginUrl(){//远程调用接口的urlString loginUrl = "http://localhost:8989/login/doLogin";OutputStream outputStream = null;InputStream inputStream = null;ByteArrayOutputStream byteArrayOutputStream = null;try {//获取压测接口的userTicketURL url = new URL(loginUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();//登录是post请求connection.setRequestMethod("POST");//post请求需要设置接口返回的数据,所以设置为trueconnection.setDoOutput(true);//参数userId和密码String param = "mobile=" + 13100000000000L + "&password=" + "123456";//获取登录接口返回的流文件outputStream = connection.getOutputStream();outputStream.write(param.getBytes(StandardCharsets.UTF_8));outputStream.flush();inputStream = connection.getInputStream();byteArrayOutputStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inputStream.read(buffer)) >= 0){byteArrayOutputStream.write(buffer, 0, len);}//获取响应结果String response = byteArrayOutputStream.toString();ObjectMapper objectMapper = new ObjectMapper();RespBean respBean = objectMapper.readValue(response, RespBean.class);String userTicket = (String) respBean.getObject();System.out.println("远程调用接口的返回值"+userTicket);//userTicket就是远程接口返回的值} catch (IOException e) {e.printStackTrace();} finally {if(byteArrayOutputStream != null){try {byteArrayOutputStream.close();} catch (IOException e) {e.printStackTrace();}}if(outputStream != null){try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}
二:RestTemplate
2.1 什么是RestTemplate
-
1.spring 框架提供的 RestTemplate 类可用于在应用中调用 rest 服务,它简化了与 http 服务的通信方式,统一了 RESTful 的标准,封装了 http 链接, 我们只需要传入 url 及返回值类型即可。相较于之前常用的 HttpClient,RestTemplate 是一种更优雅的调用 RESTful 服务的方式。
-
2.在 Spring 应用程序中访问第三方 REST 服务与使用 Spring RestTemplate 类有关。RestTemplate 类的设计原则与许多其他 Spring 模板类(例如 JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
-
3.RestTemplate 默认依赖 JDK 提供 http 连接的能力(HttpURLConnection),如果有需要的话也可以通过 setRequestFactory 方法替换为例如 Apache HttpComponents、Netty 或 OkHttp 等其它 HTTP library。
-
4.考虑到 RestTemplate 类是为调用 REST 服务而设计的,因此它的主要方法与 REST 的基础紧密相连就不足为奇了,后者是 HTTP 协议的方法:HEAD、GET、POST、PUT、DELETE 和 OPTIONS。例如,RestTemplate 类具有 headForHeaders()、getForObject()、postForObject()、put()和 delete()等方法。
2.2 配置RestTemplate
@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(){SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();//解决401报错时,报java.net.HttpRetryException: cannot retry due to server authentication, in streaming moderequestFactory.setOutputStreaming(false);RestTemplate restTemplate = new RestTemplate(requestFactory);restTemplate.setErrorHandler(new RtErrorHandler());return restTemplate;}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);factory.setConnectTimeout(15000);return factory;}
2.2 RestTemplate 添加请求头headers和请求体body
HttpHeaders header = new HttpHeaders();header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");header.set("Authorization", "authorization");HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);
- header 为需要设置的请求头
- AssetProcessVo为需要远程调用接口传递的参数
2.3 示例代码
/*** 远程调用登录接口*/public void accessLoginUrl(){HttpHeaders header = new HttpHeaders();header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");header.set("Authorization", "authorization");HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);ResponseEntity<ByteArrayOutputStream> exchange;try {//保存案件名称后,启动工作流exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ByteArrayOutputStream.class);if (exchange.getStatusCodeValue() == 200) {String response = byteArrayOutputStream.toString();ObjectMapper objectMapper = new ObjectMapper();RespBean respBean = objectMapper.readValue(response, RespBean.class);}} catch (RestClientException e) {e.printStackTrace();}
三:HttpClient
3.1 导入依赖
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency>
3.2 使用方法
1,创建HttpClient对象;
2,指定请求URL,并创建请求对象,如果是get请求则创建HttpGet对象,post则创建HttpPost对象;
3,如果请求带有参数,对于get请求可直接在URL中加上参数请求,或者使用setParam(HetpParams params)方法设置参数,对于HttpPost请求,可使用setParam(HetpParams params)方法或者调用setEntity(HttpEntity entity)方法设置参数;
4,调用httpClient的execute(HttpUriRequest request)执行请求,返回结果是一个response对象;
5,通过response的getHeaders(String name)或getAllHeaders()可获得请求头部信息,getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。
3.3 代码实现
package com.cnzz.demo.remote.rpc;import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;import java.io.IOException;/*** ************************************************************* Copyright © 2020 cnzz Inc.All rights reserved. * *** ************************************************************** @program: demo* @description:* @author: cnzz* @create: 2020-12-23 17:41**/public class HttpClientUtil {/*** httpClient的get请求方式* 使用GetMethod来访问一个URL对应的网页实现步骤:* 1.生成一个HttpClient对象并设置相应的参数;* 2.生成一个GetMethod对象并设置响应的参数;* 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;* 4.处理响应状态码;* 5.若响应正常,处理HTTP响应内容;* 6.释放连接。* @param url* @param charset* @return*/public static String doGet(String url, String charset) {//1.生成HttpClient对象并设置参数HttpClient httpClient = new HttpClient();//设置Http连接超时为5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);//2.生成GetMethod对象并设置参数GetMethod getMethod = new GetMethod(url);//设置get请求超时为5秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置请求重试处理,用的是默认的重试处理:请求三次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());String response = "";//3.执行HTTP GET 请求try {int statusCode = httpClient.executeMethod(getMethod);//4.判断访问的状态码if (statusCode != HttpStatus.SC_OK) {System.err.println("请求出错:" + getMethod.getStatusLine());}//5.处理HTTP响应内容//HTTP响应头部信息,这里简单打印Header[] headers = getMethod.getResponseHeaders();for(Header h : headers) {System.out.println(h.getName() + "---------------" + h.getValue());}//读取HTTP响应内容,这里简单打印网页内容//读取为字节数组byte[] responseBody = getMethod.getResponseBody();response = new String(responseBody, charset);System.out.println("-----------response:" + response);//读取为InputStream,在网页内容数据量大时候推荐使用//InputStream response = getMethod.getResponseBodyAsStream();} catch (HttpException e) {//发生致命的异常,可能是协议不对或者返回的内容有问题System.out.println("请检查输入的URL!");e.printStackTrace();} catch (IOException e) {//发生网络异常System.out.println("发生网络异常!");} finally {//6.释放连接getMethod.releaseConnection();}return response;}/*** post请求* @param url* @param json* @return*/public static String doPost(String url, JSONObject json){HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader("accept", "*/*");postMethod.addRequestHeader("connection", "Keep-Alive");//设置json格式传送postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");//必须设置下面这个HeaderpostMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");//添加请求参数postMethod.addParameter("commentId", json.getString("commentId"));String res = "";try {int code = httpClient.executeMethod(postMethod);if (code == 200){res = postMethod.getResponseBodyAsString();System.out.println(res);}} catch (IOException e) {e.printStackTrace();}return res;}public static void main(String[] args) {System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=telPhone", "GBK"));System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");JSONObject jsonObject = new JSONObject();jsonObject.put("commentId", "telPhone");System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));}
}