demo

package com.sza.demo;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class OpenTest {

public static String RequestMethod_get = "GET";
public static String RequestMethod_post = "POST";
public static String urlStr = "https://apitest.szca.com:19005/";// 测试
public static String clientId = "管理员分配ID";
public static String clientKey = "管理员分配key";

public static String token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNjAzODUyMTYwLCJpc3MiOiJzemNhX2V2aWRlbmNlYXV0aCIsImV4cCI6MTYwMzg1OTQ4MCwiY2xpZW50X2lkIjoidGVzdF96eWYifQ.vDOy34PU2_R5VhUFBSRRwAh1BLyY84NSHcnQIO3pUD3Jl8NM2Qe50FcGUu-jjs4Y4ANkY-zT9C8HdfBTo5dw6Q";

public static void main(String[] args) throws Exception {
// getToken();//token过期了重新运行一下方法,更新一下token
//getFileParmSend();//带文件File类型的参数请求
//getParmSend();//普通String参数请求的服务
}

/**
* 带文件类型的参数,发起http请求, 如活体检测动作+人口库服务,视频参数类型File
* 其他服务如果参数有File类型的都可以这样请求,修改一下地址和参数名即可

* @throws Exception
*/
public static void getFileParmSend() throws Exception {
String url = urlStr + "core/api/rawFaceVideoVerify?token=" + token;
Map<String, String> textMap = new HashMap<String, String>();// textMap放String类型参数
// 设置input的name,value
textMap.put("idcard_number", "张三的身份证号码");
textMap.put("idcard_name", "张三");
textMap.put("return_image_best", "1");
textMap.put("motions", "BLINK");
// 设置file的name,路径
Map<String, Object> fileMap = new HashMap<String, Object>();// fileMap放File参数
fileMap.put("video", "C:\\Users\\75119\\Desktop\\xxx.mp4");// 选择拍好的视频路径
String ret = fileUpload(url, textMap, fileMap);

System.out.println(ret);
}

/**
* 普通参数发起http请求, 如简项查询,参数都是string类型, 其他服务如果参数是String类型的都可以这样请求,修改一下地址和参数名即可

* @throws Exception
*/
public static void getParmSend() throws Exception {
String url = urlStr + "core/api/idcard_check?token=" + token;
Map<String, String> textMap = new HashMap<String, String>();
// 设置input的name,value
textMap.put("idcard_number", "张三的身份证号码");
textMap.put("idcard_name", "张三");
String ret = sendPost(url, textMap);
System.out.println(ret);
}

/**
* 获取token

* @throws Exception
*/
public static void getToken() throws Exception {
String url = urlStr + "authServer/auth/token/%s/%s";
String ret = HttpRequest(String.format(url, clientId, clientKey), RequestMethod_get, null);
System.out.println(ret);
}

/**
* 发起https请求并获取结果

* @param requestUrl    请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr     提交的数据
* @throws Exception
*/
public static String HttpRequest(String request, String RequestMethod, String output) throws Exception {
StringBuffer buffer = new StringBuffer();
String ret = "";
try {
// 建立连接
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(RequestMethod);
if (output != null) {
OutputStream out = connection.getOutputStream();
out.write(output.getBytes("UTF-8"));
out.close();
}

// 流处理
InputStream input = null;
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
input = connection.getInputStream();
} else {
input = connection.getErrorStream();
}

InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");
BufferedReader reader = new BufferedReader(inputReader);
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
// 关闭连接、释放资源
reader.close();
inputReader.close();
input.close();
input = null;
connection.disconnect();
ret = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return ret;
}

/**
* 表单提交参数

* @param urlStr  地址
* @param textMap 普通参数
* @return
*/
public static String sendPost(String urlStr, Map<String, String> textMap) {
return fileUpload(urlStr, textMap, null);

}

/**
* 表单提交文件

* @param urlStr  地址
* @param textMap 普通参数
* @param objMap  文件
* @return
*/
@SuppressWarnings("rawtypes")
public static String fileUpload(String urlStr, Map<String, String> textMap, Map<String, Object> objMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "-----------------12345654321-----------";
try {
URL url = new URL(urlStr);
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(50000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(RequestMethod_post);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Charset", "UTF-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes("UTF-8"));
}
if (objMap != null) {
Iterator iter = objMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:application/octet-stream" + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 流处理
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} else {
StringBuffer error = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), "UTF-8"));
String line1 = null;
while ((line1 = bufferedReader.readLine()) != null) {
error.append(line1).append("\n");
}
res = error.toString();
bufferedReader.close();
bufferedReader = null;
}

} catch (Exception e) {
System.out.println("发送POST请求出错。" + e);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;

}

// 解决PKIX path building failed问题,在代码中必须要忽略证书信任问题
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}

public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}

}