1. com.ffcs.ebp.ebpsdk.common.Response
package com.ffcs.ebp.ebpsdk.common;
import java.util.Map;
public class Response {
private int statusCode;
private String body;
private Map<String,String> headers;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
}
2. com.ffcs.ebp.ebpsdk.YunSign
package com.ffcs.ebp.ebpsdk;
import com.ffcs.ebp.ebpsdk.common.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
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.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;
public class YunSign {
private String url;
private String body;
private String ak;
private String sk;
private String uuId;
private int temp;
private String contentType;
private String queryStr;
private Map<String, Object> headerMap;
private String afterQuery;
public YunSign(String url, String ak, String sk, String uuId, String body, int temp, String contentType, String queryStr, Map<String, Object> headerMap) {
this.url = url;
if(body.equals("{}")){
body = "";
}
this.body = body;
this.ak = ak;
this.sk = sk;
this.uuId = uuId;
this.temp = temp;
this.contentType = contentType;
this.queryStr = queryStr;
this.headerMap = headerMap;
}
public Response toDo(String method, int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
Response response = null;
method = method.toUpperCase();
switch (method) {
case "POST":
response = doPost(connectTimeout, connectionRequestTimeout, socketTimeout);
break;
case "GET":
if (StringUtils.isNotEmpty(this.body)) {
response = sendJsonByGetReq(connectTimeout, connectionRequestTimeout, socketTimeout);
} else {
response = doGet(connectTimeout, connectionRequestTimeout, socketTimeout);
}
break;
case "DELETE":
if (StringUtils.isNotEmpty(this.body)) {
response = sendJsonByDeleteReq(connectTimeout, connectionRequestTimeout, socketTimeout);
} else {
response = doDelete(connectTimeout, connectionRequestTimeout, socketTimeout);
}
break;
case "PUT":
response = doPut(connectTimeout, connectionRequestTimeout, socketTimeout);
break;
case "PATCH":
response = doPatch(connectTimeout, connectionRequestTimeout, socketTimeout);
break;
case "HEAD":
response = doHead(connectTimeout, connectionRequestTimeout, socketTimeout);
break;
}
return response;
}
private String getSign(Date eopDate) {
String calculateContentHash = getSHA256(body); //报文原封不动进行sha256摘要
// System.out.println("calculateContentHash:" + calculateContentHash);
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyyMMdd");
String singerDate = TIME_FORMATTER.format(eopDate);
String singerDd = DATE_FORMATTER.format(eopDate);
//header的key按照26字母进行排序, 以&作为连接符连起来
try {
String CampmocalHeader = String.format("ctyun-eop-request-id:%s\neop-date:%s\n", this.uuId, singerDate);
String sigture = CampmocalHeader + "\n" + this.afterQuery + "\n" + calculateContentHash;
// System.out.println("sigture:" + sigture);
byte[] ktime = HmacSHA256(singerDate.getBytes(), sk.getBytes());
// System.out.println("ktime:" + HexUtils.bytes2Hex(ktime));
byte[] kAk = HmacSHA256(ak.getBytes(), ktime);
// System.out.println("kAk:" + HexUtils.bytes2Hex(kAk));
byte[] kdate = HmacSHA256(singerDd.getBytes(), kAk);
// System.out.println("kdate:" + HexUtils.bytes2Hex(kdate));
String Signature = Base64.getEncoder().encodeToString(HmacSHA256(sigture.getBytes("UTF-8"), kdate));
// System.out.println("---Signature:" + Signature);
String signHeader = String.format("%s Headers=ctyun-eop-request-id;eop-date Signature=%s", ak, Signature);
// System.out.println("---signHeader:" + signHeader);
return signHeader;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 在调用SSL之前需要重写验证方法,取消检测SSL
* 创建ConnectionManager,添加Connection配置信息
*
* @return HttpClient 支持https
*/
private static CloseableHttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法,取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
public Response doGet(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Response result = new Response();
try {
// 通过址默认配置创建一个httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
//创建HttpGet远程连接实例
HttpGet httpGet;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpGet = new HttpGet(this.url + "?" + this.afterQuery);
} else {
httpGet = new HttpGet(this.url);
}
// 设置请求头信息,鉴权
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpGet.setHeader("Content-Type", this.contentType);
httpGet.setHeader("ctyun-eop-request-id", this.uuId);
httpGet.setHeader("Eop-Authorization", getSign(eopDate));
httpGet.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpGet.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpGet.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 请求超时时间
.setSocketTimeout(socketTimeout)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(response.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : response.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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 Response sendJsonByGetReq(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
Response result = new Response();
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 通过址默认配置创建一个httpClient实例
if (temp == 0) {//绕过SSL
client = sslClient();
} else {
client = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建HttpGetWithEntity远程连接实例
HttpGetWithEntity httpGetWithEntity;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpGetWithEntity = new HttpGetWithEntity(this.url + "?" + this.afterQuery);
} else {
httpGetWithEntity = new HttpGetWithEntity(this.url);
}
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 设置连接请求超时时间
.setSocketTimeout(socketTimeout)// 设置读取数据连接超时时间
.build();
// 为HttpGetWithEntity实例设置配置
httpGetWithEntity.setConfig(requestConfig);
// 设置请求头
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpGetWithEntity.setHeader("Content-Type", this.contentType);
httpGetWithEntity.setHeader("ctyun-eop-request-id", this.uuId);
httpGetWithEntity.setHeader("Eop-Authorization", getSign(eopDate));
httpGetWithEntity.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpGetWithEntity.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpGetWithEntity.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
HttpEntity httpEntity = new StringEntity(body, Charset.forName("UTF-8"));
httpGetWithEntity.setEntity(httpEntity);
//执行请求操作,并拿到结果(同步阻塞)
response = client.execute(httpGetWithEntity);
//获取结果实体
HttpEntity entity = response.getEntity();
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(response.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : response.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != client) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public Response doPost(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
Response result = new Response();
try {
// 创建httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建httpPost远程连接实例
HttpPost httpPost;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpPost = new HttpPost(this.url + "?" + this.afterQuery);
} else {
httpPost = new HttpPost(this.url);
}
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 设置连接请求超时时间
.setSocketTimeout(socketTimeout)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
// 设置请求头
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpPost.setHeader("Content-Type", this.contentType);
httpPost.setHeader("ctyun-eop-request-id", this.uuId);
httpPost.setHeader("Eop-Authorization", getSign(eopDate));
httpPost.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpPost.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpPost.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 为httpPost设置封装好的请求参数
StringEntity data = new StringEntity(body, Charset.forName("UTF-8"));
httpPost.setEntity(data);
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpPost);
// 从响应对象中获取响应内容
HttpEntity entity = httpResponse.getEntity();
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(httpResponse.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : httpResponse.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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;
}
public Response doPut(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
Response result = new Response();
try {
// 创建httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建HttpPut远程连接实例
HttpPut httpPut;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpPut = new HttpPut(this.url + "?" + this.afterQuery);
} else {
httpPut = new HttpPut(this.url);
}
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 设置连接请求超时时间
.setSocketTimeout(socketTimeout)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPut.setConfig(requestConfig);
// 设置请求头
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date(2032-1900,01,05);
httpPut.setHeader("Content-Type", this.contentType);
httpPut.setHeader("ctyun-eop-request-id", this.uuId);
httpPut.setHeader("Eop-Authorization", getSign(eopDate));
httpPut.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpPut.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpPut.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 为httpPost设置封装好的请求参数
StringEntity data = new StringEntity(body, Charset.forName("UTF-8"));
httpPut.setEntity(data);
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpPut);
// 从响应对象中获取响应内容
HttpEntity entity = httpResponse.getEntity();
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(httpResponse.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : httpResponse.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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;
}
public Response doPatch(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
Response result = new Response();
try {
// 创建httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建HttpPatch远程连接实例
HttpPatch httpPatch;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpPatch = new HttpPatch(this.url + "?" + this.afterQuery);
} else {
httpPatch = new HttpPatch(this.url);
}
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 设置连接请求超时时间
.setSocketTimeout(socketTimeout)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPatch.setConfig(requestConfig);
// 设置请求头
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpPatch.setHeader("Content-Type", this.contentType);
httpPatch.setHeader("ctyun-eop-request-id", this.uuId);
httpPatch.setHeader("Eop-Authorization", getSign(eopDate));
httpPatch.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpPatch.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpPatch.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 为httpPost设置封装好的请求参数
StringEntity data = new StringEntity(body, Charset.forName("UTF-8"));
httpPatch.setEntity(data);
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpPatch);
// 从响应对象中获取响应内容
HttpEntity entity = httpResponse.getEntity();
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(httpResponse.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : httpResponse.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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;
}
public Response doDelete(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Response result = new Response();
try {
// 通过址默认配置创建一个httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建httpGet远程连接实例
HttpDelete httpDelete;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpDelete = new HttpDelete(this.url + "?" + this.afterQuery);
} else {
httpDelete = new HttpDelete(this.url);
}
// 设置请求头信息,鉴权
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpDelete.setHeader("Content-Type", this.contentType);
httpDelete.setHeader("ctyun-eop-request-id", this.uuId);
httpDelete.setHeader("Eop-Authorization", getSign(eopDate));
httpDelete.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpDelete.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpDelete.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 请求超时时间
.setSocketTimeout(socketTimeout)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpDelete.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpDelete);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(response.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : response.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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 Response sendJsonByDeleteReq(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Response result = new Response();
try {
// 通过址默认配置创建一个httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建httpGet远程连接实例
HttpDeleteWithBody delete;
if (StringUtils.isNotEmpty(this.afterQuery)) {
delete = new HttpDeleteWithBody(this.url + "?" + this.afterQuery);
} else {
delete = new HttpDeleteWithBody(this.url);
}
// 设置请求头信息,鉴权
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
delete.setHeader("Content-Type", this.contentType);
delete.setHeader("ctyun-eop-request-id", this.uuId);
delete.setHeader("Eop-Authorization", getSign(eopDate));
delete.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
delete.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : delete.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
HttpEntity httpEntity = new StringEntity(body, Charset.forName("UTF-8"));
delete.setEntity(httpEntity);
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 请求超时时间
.setSocketTimeout(socketTimeout)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
delete.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(delete);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(response.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : response.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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 Response doHead(int connectTimeout, int connectionRequestTimeout, int socketTimeout) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Response result = new Response();
try {
// 通过址默认配置创建一个httpClient实例
if (temp == 0) {//绕过SSL
httpClient = sslClient();
} else {
httpClient = HttpClients.createDefault();
}
String query = this.queryStr;
this.afterQuery = encodeQueryStr(query);
// 创建httpHead远程连接实例
HttpHead httpHead;
if (StringUtils.isNotEmpty(this.afterQuery)) {
httpHead = new HttpHead(this.url + "?" + this.afterQuery);
} else {
httpHead = new HttpHead(this.url);
}
// 设置请求头信息,鉴权
SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Date eopDate = new Date();
httpHead.setHeader("Content-Type", this.contentType);
httpHead.setHeader("ctyun-eop-request-id", this.uuId);
httpHead.setHeader("Eop-Authorization", getSign(eopDate));
httpHead.setHeader("Eop-date", TIME_FORMATTER.format(eopDate));
if (this.headerMap != null) {
for (String key : this.headerMap.keySet()) {
if (StringUtils.isNotEmpty(key)) {
httpHead.setHeader(key, this.headerMap.get(key).toString());
}
}
}
System.out.println("请求头部 ----- ");
for (Header header : httpHead.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
System.out.println();
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)// 连接主机服务超时时间
.setConnectionRequestTimeout(connectionRequestTimeout)// 请求超时时间
.setSocketTimeout(socketTimeout)// 数据读取超时时间
.build();
// 为httpHead实例设置配置
httpHead.setConfig(requestConfig);
// 执行head请求得到返回对象
response = httpClient.execute(httpHead);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result.setBody(EntityUtils.toString(entity, "UTF-8"));
result.setStatusCode(response.getStatusLine().getStatusCode());
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : response.getAllHeaders()) {
headerMap.put(header.getName(), header.getValue());
}
result.setHeaders(headerMap);
} catch (Exception 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;
}
private String toHex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length * 2);
byte[] var2 = data;
int var3 = data.length;
for (int var4 = 0; var4 < var3; ++var4) {
byte b = var2[var4];
String hex = Integer.toHexString(b);
if (hex.length() == 1) {
sb.append("0");
} else if (hex.length() == 8) {
hex = hex.substring(6);
}
sb.append(hex);
}
return sb.toString().toLowerCase(Locale.getDefault());
}
private String getSHA256(String text) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes(StandardCharsets.UTF_8));
return toHex(md.digest());
} catch (NoSuchAlgorithmException var3) {
return null;
}
}
public byte[] HmacSHA256(byte[] data, byte[] key) throws Exception {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data);
} catch (Exception e) {
return null;
}
}
public String encodeQueryStr(String query) {
String afterQuery = "";
try {
if (StringUtils.isNotEmpty(query)) {
String param[] = query.split("&");
Arrays.sort(param);
for (String str : param) {
if (afterQuery.length() < 1) {
String[] s = str.split("=");
if (s.length >= 2) {
String encodeStr = null;
encodeStr = URLEncoder.encode(s[1], "UTF-8");
str = s[0] + "=" + encodeStr;
afterQuery = afterQuery + str;
} else {
String encodeStr = "";
str = s[0] + "=" + encodeStr;
afterQuery = afterQuery + str;
}
} else {
String[] s = str.split("=");
if (s.length >= 2) {
String encodeStr = URLEncoder.encode(s[1], "UTF-8");
str = s[0] + "=" + encodeStr;
afterQuery = afterQuery + "&" + str;
} else {
String encodeStr = "";
str = s[0] + "=" + encodeStr;
afterQuery = afterQuery + "&" + str;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return afterQuery;
}
}
3. HexUtils.java
package com.ffcs.ebp.ebpsdk;
public class HexUtils {
private static final char[] HEXES = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
/**
* byte数组 转换成 16进制小写字符串
*/
public static String bytes2Hex(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(HEXES[(b >> 4) & 0x0F]);
hex.append(HEXES[b & 0x0F]);
}
return hex.toString();
}
/**
* 16进制字符串 转换为对应的 byte数组
*/
public static byte[] hex2Bytes(String hex) {
if (hex == null || hex.length() == 0) {
return null;
}
char[] hexChars = hex.toCharArray();
byte[] bytes = new byte[hexChars.length / 2]; // 如果 hex 中的字符不是偶数个, 则忽略最后一个
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt("" + hexChars[i * 2] + hexChars[i * 2 + 1], 16);
}
return bytes;
}
}
4. HttpDeleteWithBody.java
package com.ffcs.ebp.ebpsdk;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase{
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
5. HttpGetWithEntity.java
package com.ffcs.ebp.ebpsdk;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
private final static String METHOD_NAME = "GET";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
}
6. MyTest.java
import com.ffcs.ebp.ebpsdk.YunSign;
import com.ffcs.ebp.ebpsdk.common.Response;
import java.util.*;
public class MyTest {
public static void main(String[] args) throws Exception {
//0:绕过ssl证书 1:验证ssl证书
int temp = 1;
//请求方式
String method = "get";
//请求类型
String contentType = "application/json;charset=UTF-8"; //application/x-www-form-urlencoded;charset=UTF-8
//String contentType = "application/x-www-form-urlencoded;charset=UTF-8";
// String contentType = "multipart/form-data;charset=UTF-8";
//header头参数添加(没有就不填)
Map<String, Object> headerMap = new HashMap<>();
// headerMap.put("queryMetricDataInfo", "{\"regionId\":\"cn-sz1\",\"dim\":\"instance_id,98cdcc8a-8e54-4788-ab9c-c94ccee429c7\",\"filter\":\"average\",\"from\":\"1658473040\",\"to\":\"1658473040\",\"metricName\":\"net_bitRecv\",\"namespace\":\"AGT.ECS\",\"period\":\"1\"},\"platform\":\"3\"}");
// headerMap.put("platform", "3");
// headerMap.put("consoleUrl", "http://55.242.31.61:4802");
// headerMap.put("User-Agent", "3333433");
// headerMap.put("X-Forwarded-For", "1231313");
// headerMap.put("regionId", "100054c0416811e9a6690242ac110002");
// headerMap.put("prodInstId","9dcaf0157c604100af79bdb8271527bc");
//请求地址
String url = "https://zos-global.ctapi.ctyun.cn/v4/oss/list-buckets";
//query参数(?后面拼接的参数。没有就不填) aa=aa&bb=bb
String queryStr = "regionID=41f64827xxxxxxxxxffa3a5deb5d15d";
//body参数(没有就不填)
String body = "";
//APPID
String ak = "9f82cacd3f8235c66edfs5e899f098e6";
//appkey
String sk = "MlgzESz430hJgTzA4lkjuJvDMMLTqwBQRicVqV62-VM";
//ctyun-eop-request-id(32位uuid)
String uuId = UUID.randomUUID().toString();
//连接超时
int connectTimeout = 35000;
//连接请求超时
int connectionRequestTimeout = 35000;
//socket超时
int socketTimeout = 60000;
YunSign yunSign = new YunSign(url, ak, sk, uuId, body, temp, contentType, queryStr, headerMap);
Response response = yunSign.toDo(method, connectTimeout, connectionRequestTimeout, socketTimeout);
System.out.println("应答头部 ----- ");
for (Map.Entry entry : response.getHeaders().entrySet()) {
System.out.println(entry.getKey().toString() + ":" + entry.getValue().toString());
}
System.out.println();
System.out.println("请求结果 ----- ");
System.out.println(response.getBody());
}
}