目录
Get接口调用入口
public void invokeGetRequest() {
//设置请求头
HashMap<String, String> header = new HashMap<>();
header.put("Accept", "*/*");
header.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
header.put("Content-Type", "application/json;charset=utf-8");
//调用GET接口
doGet("https://127.1.1.1:7443/api/v1/query", header);
}
GET请求接口调用
/**
* GET请求接口调用
* @param uri https://1.1.1.1:2001/api/getrequest
* @param header 请求头
*/
public static void doGet(String uri, HashMap<String, String> header) {
HttpsURLConnection httpsConn = null;
try {
//获取连接
httpsConn = getHttpsURLConnection(uri, "GET", header);
//获取接口响应状态码(200,401,500...)
int responseCode = httpsConn.getResponseCode();
System.out.println("接口响应状态码" + responseCode);
if (responseCode == 200) {
//读取HTTP响应内容,读取为字节数组,再转为字符串
try (InputStream in = httpsConn.getInputStream()) {
byte[] b = getBytesFromStream(in);
String responseResult = new String(b);
System.out.println("调用接口成功,响应结果:" + responseResult);
}
} else {
System.out.println("接口响应状态码:" + responseCode);
}
} catch (HTTPException e) {
System.out.println("请检查输入的URL!可能是协议不对或者返回的内容有问题");
e.printStackTrace();
} catch (IOException e) {
System.out.println("发生网络异常!");
e.printStackTrace();
} finally {
//关闭远程连接
disconnect(httpsConn);
}
}
POST接口调用入口
public void invokePostRequest() {
//设置请求头
HashMap<String, String> header = new HashMap<>();
header.put("Accept", "*/*");
header.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
header.put("Content-Type", "application/json;charset=utf-8");
//设置请求参数
Map<String, Object> bodyMap = new HashMap<>();
bodyMap.put("id","111");
Gson gson = new Gson();
String body = gson.toJson(bodyMap);
//调用POST接口
doPost("https://127.1.1.1:7443/api/v1/query", body,header);
}
POST请求接口调用
public static String doPost(String uri, String data, HashMap<String, String> header) throws IOException {
HttpsURLConnection conn = getHttpsURLConnection(uri, "POST", header);
//设置参数
setBytesToStream(conn, data);
try (InputStream in = conn.getInputStream()) {
byte[] b = getBytesFromStream(in);
return new String(b);
} finally {
disconnect(conn);
}
}
获取URL连接
/**
* 获取URL连接
*/
public static HttpsURLConnection getHttpsURLConnection(String uri, String method, HashMap<String, String> header) throws IOException {
SSLContext ctx;
try {
ctx = SSLContext.getInstance("SSL");
ctx.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
} catch (Exception e) {
System.out.println("Failed to get http connection.");
throw new IOException();
}
SSLSocketFactory ssf = ctx.getSocketFactory();
//创建连接
URL url = new URL(uri);
HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
//绕过HTTPS相关证书关键代码-开始
httpsConn.setSSLSocketFactory(ssf);
//绕过HTTPS相关证书关键代码-结束
httpsConn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
if (verifySSL(hostname, session)) {
return true;
}
return false;
}
private boolean verifySSL(String hostname, SSLSession session) {
String peerHost = (session == null) ? "" : session.getPeerHost();
System.out.println("verify https url, hostname:" + hostname + ", peerHost: " + peerHost);
return true;
}
});
//设置连接方式(GET,POST...)
httpsConn.setRequestMethod(method);
//当前向远程服务读取数据时,设置为true
httpsConn.setDoInput(true);
//当向远程服务器传送数据/写数据时,需要设置为true
httpsConn.setDoOutput(true);
//设置连接超时时间30s(时间根据情况自己设置)
httpsConn.setConnectTimeout(30 * 1000);
//设置响应读取时间
httpsConn.setReadTimeout(30 * 1000);
httpsConn.setRequestProperty("Connection", "Keep-Alive");
if (header != null) {
for (String key : header.keySet()) {
httpsConn.setRequestProperty(key, header.get(key));
}
}
return httpsConn;
}
private static final class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) { }
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) { }
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
将输入流转为byte数组
/**
* 将输入流转为byte数组
*/
public static byte[] getBytesFromStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] kb = new byte[1024];
int len;
while ((len = is.read(kb)) != -1) {
baos.write(kb, 0, len);
}
byte[] bytes = baos.toByteArray();
baos.close();
is.close();
return bytes;
}
post请求中发送请求参数
public static void setBytesToStream(HttpsURLConnection conn, String data) throws IOException {
if (null == data) {
return;
}
byte[] kb = new byte[1024];
int len;
try (OutputStream os = conn.getOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes())) {
while ((len = bais.read(kb)) != -1) {
os.write(kb, 0, len);
}
os.flush();
}
}
断开连接
public static void disconnect(HttpsURLConnection conn) {
try {
conn.disconnect();
} catch (Exception e) {
System.out.println("Disconnect fail");
}
}