一、为啥要整理呢?
工作一年,遇见了多种发送请求的方式,但对这方面的整理还是只鳞片解,不说详细了解,单纯的概念和使用还是需要整理一波的,淦起来。下面稍微讲解下http和https,不需要的同学可以直接跳过,这块简而言之,如果是https地址,在后端发送请求时,确定是否带上证书或忽略证书即可。
1.1 http和https
1.1.1 HTTP和HTTPS的基本概念
HTTP:是互联网上应用最为广泛的一种网络协议,是一个客户端和服务器端请求和应答的标准(TCP),用于从WWW服务器传输超文本到本地浏览器的传输协议,它可以使浏览器更加高效,使网络传输减少。
HTTPS:是以安全为目标的HTTP通道,简单讲是HTTP的安全版,即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL。
HTTPS协议的主要作用可以分为两种:一种是建立一个信息安全通道,来保证数据传输的安全;另一种就是确认网站的真实性。
1.1.2 HTTP与HTTPS有什么区别?
HTTP协议传输的数据都是未加密的,也就是明文的,因此使用HTTP协议传输隐私信息非常不安全,为了保证这些隐私数据能加密传输,于是网景公司设计了SSL(Secure Sockets Layer)协议用于对HTTP协议传输的数据进行加密,从而就诞生了HTTPS。简单来说,HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,要比http协议安全。
HTTPS和HTTP的区别主要如下:
1、https协议需要到ca申请证书,一般免费证书较少,因而需要一定费用。
2、http是超文本传输协议,信息是明文传输,https则是具有安全性的ssl加密传输协议。
3、http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。
4、http的连接很简单,是无状态的;HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,比http协议安全。
1.1.2 HTTPS的工作原理
我们都知道HTTPS能够加密信息,以免敏感信息被第三方获取,所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议。
客户端在使用HTTPS方式与Web服务器通信时有以下几个步骤,如图所示。
(1)客户使用https的URL访问Web服务器,要求与Web服务器建立SSL连接。
(2)Web服务器收到客户端请求后,会将网站的证书信息(证书中包含公钥)传送一份给客户端。
(3)客户端的浏览器与Web服务器开始协商SSL连接的安全等级,也就是信息加密的等级。
(4)客户端的浏览器根据双方同意的安全等级,建立会话密钥,然后利用网站的公钥将会话密钥加密,并传送给网站。
(5)Web服务器利用自己的私钥解密出会话密钥。
(6)Web服务器利用会话密钥加密与客户端之间的通信。
二、java实现请求的五种方式
目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。
HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,
HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,
但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程
url的工具包,最新的;
另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种
实现方式。
2.1 Java原生HttpURLConnection
package com.powerX.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClient {
public static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 关闭远程连接
}
return result;
}
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
connection.disconnect();
}
return result;
}
}
2.2 apache HttpClient3.1
package com.powerX.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClient3 {
public static String doGet(String url) {
// 输入流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例
HttpClient httpClient = new HttpClient();
// 设置http连接主机服务超时时间:15000毫秒
// 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建一个Get方法实例对象
GetMethod getMethod = new GetMethod(url);
// 设置get请求超时为60000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
try {
// 执行Get方法
int statusCode = httpClient.executeMethod(getMethod);
// 判断返回码
if (statusCode != HttpStatus.SC_OK) {
// 如果状态码返回的不是ok,说明失败了,打印错误信息
System.err.println("Method faild: " + getMethod.getStatusLine());
} else {
// 通过getMethod实例,获取远程的一个输入流
is = getMethod.getResponseBodyAsStream();
// 包装输入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
// 读取封装的输入流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
getMethod.releaseConnection();
}
return result;
}
public static String doPost(String url, Map<String, Object> paramMap) {
// 获取输入流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建post请求方法实例对象
PostMethod postMethod = new PostMethod(url);
// 设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
NameValuePair[] nvp = null;
// 判断参数map集合paramMap是否为空
if (null != paramMap && paramMap.size() > 0) {// 不为空
// 创建键值参数对象数组,大小为参数的个数
nvp = new NameValuePair[paramMap.size()];
// 循环遍历参数集合map
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
// 获取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
int index = 0;
while (iterator.hasNext()) {
Entry<String, Object> mapEntry = iterator.next();
// 从mapEntry中获取key和value创建键值对象存放到数组中
try {
nvp[index] = new NameValuePair(mapEntry.getKey(),
new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
index++;
}
}
// 判断nvp数组是否为空
if (null != nvp && nvp.length > 0) {
// 将参数存放到requestBody对象中
postMethod.setRequestBody(nvp);
}
// 执行POST方法
try {
int statusCode = httpClient.executeMethod(postMethod);
// 判断是否成功
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method faild: " + postMethod.getStatusLine());
}
// 获取远程返回的数据
is = postMethod.getResponseBodyAsStream();
// 封装输入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
postMethod.releaseConnection();
}
return result;
}
}
2.3 apache httpClient4.5
package com.powerX.httpClient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClient4 {
public static String doGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 设置请求头信息,鉴权
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String doPost(String url, Map<String, Object> paramMap) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String result = "";
// 创建httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
.setSocketTimeout(60000)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
// 设置请求头
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 封装post请求参数
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 通过map集成entrySet方法获取entity
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
// 循环遍历,获取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, Object> mapEntry = iterator.next();
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
// 为httpPost设置封装好的请求参数
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpPost);
// 从响应对象中获取响应内容
HttpEntity entity = httpResponse.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
2.4 Unirest
unirest 是一套跨语言轻量级HTTP开发库,由Kong团队维护,此团队同时维护着另一个著名开源网关项目API Gateway Kong(有兴趣的一定要去了解哇)。而且这个方式代码量十分少,十分方便。
这里仅介绍单纯的Get调用方式。详细的可以去这篇博客看==>UniRest 使用手册
@Override
public String checkGAInterface(String jobId) {
String result = "";
String responseStr = "成功";
GaMonitor gaMonitor = gaMonitorMapper.selectById(jobId);
String jobStatus = gaMonitor.getJobStatus();
try {
//返回数据
HttpHeaders headers = new HttpHeaders();
//设置忽略证书,因为我这里配置的是https的内网地址。
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpResponse<String> resultPost=Unirest.post(GaContants.GA_CHECK_JOB_URL+jobId+"?token="+GaContants.GA_TOKEN_WEB+"&f=json")
.contentType(io.joshworks.restclient.http.MediaType.APPLICATION_FORM_URLENCODED)
.asString();
result = resultPost.getBody();
//返回数据
JSONObject resultData = JSONObject.parseObject(result);
System.out.println(resultData);
Object jobStatusNext = resultData.get("jobStatus");
Object messages = resultData.get("messages");
if(jobId==null||jobStatus==null){
responseStr = "未获取到GA接口信息";
return responseStr;
}
gaMonitor.setJobStatus(jobStatusNext.toString());
if(messages != null){
gaMonitor.setMessage(messages.toString());
}
} catch (RestClientException e) {
log.error("Ga数据请求或解析异常->>>"+e);
}
gaMonitorMapper.updateById(gaMonitor);
return responseStr;
}
2.5 RestTemplate
RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。同时它支持负载均衡,这里不详细赘述,仅介绍请求方式。这里有篇博客可以稍微参考==>RestTemplate发送HTTP、HTTPS请求。
//返回数据
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(pa, headers);
//url+请求配置
result = unSslRestTemplate.postForObject(GaContants.GA_SUBMIT_JOB_URL, request, String.class);
三、补充
1、侵删;
2、后续等接触了解更多会继续完善。
3、只讲实现,也希望抱有理想。