Http 请求

package com.ecton;

import com.alibaba.fastjson.JSONArray;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.net.ssl.HttpsURLConnection;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


public class HttpClientTest {
/**
* 目标地址
*/
private URL url;

/**
* 通信连接超时时间
*/
private int connectionTimeout;

/**
* 通信读超时时�?
*/
private int readTimeOut;

/**
* 通信结果
*/
private String result;

/**
* 获取通信结果
*
* @return
*/
public String getResult() {
return result;
}

/**
* 设置通信结果
*
* @param result
*/
public void setResult(String result) {
this.result = result;
}

/**
* 构�?函数
*
* @param url 目标地址
* @param connectionTimeout HTTP连接超时时间
* @param readTimeOut HTTP读写超时时间
*/
public HttpClientTest(String url, int connectionTimeout, int readTimeOut) {
try {
this.url = new URL(url);
this.connectionTimeout = connectionTimeout;
this.readTimeOut = readTimeOut;
} catch (MalformedURLException e) {
}
}

/**
* 发�?信息到服务端
*
* @param data
* @param encoding
* @return
* @throws Exception
*/
public int send(Map<String, String> data, String encoding) throws Exception {
try {
HttpURLConnection httpURLConnection = createConnection(encoding);
if (null == httpURLConnection) {
throw new Exception("创建联接失败");
}
String sendData = this.getRequestParamString(data, encoding);
this.requestServer(httpURLConnection, sendData,
encoding);
this.result = this.response(httpURLConnection, encoding);
return httpURLConnection.getResponseCode();
} catch (Exception e) {
throw e;
}
}

/**
* 发�?信息到服务端 GET方式
*
* @param encoding
* @return
* @throws Exception
*/
public int sendGet(String encoding) throws Exception {
try {
HttpURLConnection httpURLConnection = createConnectionGet(encoding);
if (null == httpURLConnection) {
throw new Exception("创建联接失败");
}
this.result = this.response(httpURLConnection, encoding);
return httpURLConnection.getResponseCode();
} catch (Exception e) {
throw e;
}
}


/**
* HTTP Post发�?消息
*
* @param connection
* @param message
* @throws IOException
*/
private void requestServer(final URLConnection connection, String message, String encoder)
throws Exception {
PrintStream out = null;
try {
connection.connect();
out = new PrintStream(connection.getOutputStream(), false, encoder);
out.print(message);
out.flush();
} catch (Exception e) {
throw e;
} finally {
if (null != out) {
out.close();
}
}
}

/**
* 显示Response消息
*
* @param connection
* @return
* @throws URISyntaxException
* @throws IOException
*/
private String response(final HttpURLConnection connection, String encoding)
throws Exception {
InputStream in = null;
StringBuilder sb = new StringBuilder(1024);
BufferedReader br = null;
try {
if (200 == connection.getResponseCode()) {
in = connection.getInputStream();
sb.append(new String(read(in), encoding));
} else {
in = connection.getErrorStream();
sb.append(new String(read(in), encoding));
}
return sb.toString();
} catch (Exception e) {
throw e;
} finally {
if (null != br) {
br.close();
}
if (null != in) {
in.close();
}
if (null != connection) {
connection.disconnect();
}
}
}

public static byte[] read(InputStream in) throws IOException {
byte[] buf = new byte[1024];
int length = 0;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((length = in.read(buf, 0, buf.length)) > 0) {
bout.write(buf, 0, length);
}
bout.flush();
return bout.toByteArray();
}

/**
* 创建连接
*
* @return
* @throws ProtocolException
*/
private HttpURLConnection createConnection(String encoding) throws ProtocolException {
HttpURLConnection httpURLConnection = null;
try {
if ("https".equalsIgnoreCase(url.getProtocol())) {
String urlStr = url.toString();
url = new URL(null, urlStr, new sun.net.www.protocol.https.Handler());//https请求用sun.net.www.protocol.https.Handler
httpURLConnection = (HttpURLConnection) url.openConnection();
} else {
httpURLConnection = (HttpURLConnection) url.openConnection();
}
} catch (IOException e) {
return null;
}
httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
httpURLConnection.setDoInput(true); // 可读
httpURLConnection.setDoOutput(true); // 可写
httpURLConnection.setUseCaches(false);// 取消缓存
httpURLConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded;charset=" + encoding);
httpURLConnection.setRequestMethod("POST");
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情�?
return husn;
}
return httpURLConnection;
}

/**
* 创建连接
*
* @return
* @throws ProtocolException
*/
private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException {
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
return null;
}
httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
httpURLConnection.setUseCaches(false);// 取消缓存
httpURLConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded;charset=" + encoding);
httpURLConnection.setRequestMethod("GET");
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情�?
return husn;
}
return httpURLConnection;
}

/**
* 将Map存储的对象,转换为key=value&key=value的字�?
*
* @param requestParam
* @param coder
* @return
*/
private String getRequestParamString(Map<String, String> requestParam, String coder) {
if (null == coder || "".equals(coder)) {
coder = "UTF-8";
}
StringBuffer sf = new StringBuffer("");
String reqstr = "";
if (null != requestParam && 0 != requestParam.size()) {
for (Entry<String, String> en : requestParam.entrySet()) {
try {
sf.append(en.getKey()
+ "="
+ (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
.encode(en.getValue(), coder)) + "&");
} catch (UnsupportedEncodingException e) {
return "";
}
}
reqstr = sf.substring(0, sf.length() - 1);
}
return reqstr;
}

/**
* 发�?信息到服务端(报文json)
*
* @param data
* @param encoding
* @return
* @throws Exception
*/
public int sendWithJson(String data, String encoding) throws Exception {
try {
HttpURLConnection httpURLConnection = createConnection(encoding);
if (null == httpURLConnection) {
throw new Exception("创建联接失败");
}
this.requestServer(httpURLConnection, data,
encoding);
this.result = this.response(httpURLConnection, encoding);
return httpURLConnection.getResponseCode();
} catch (Exception e) {
throw e;
}
}


/**
* 发�?信息到服务端
*
* @param data
* @param encoding
* @return
* @throws Exception
*/
public int sendByJson(String data, String encoding) throws Exception {
try {
HttpURLConnection httpURLConnection = createConnectionByJSON(encoding);
if (null == httpURLConnection) {
throw new Exception("创建联接失败");
}
this.requestServer(httpURLConnection, data,
encoding);
System.out.println("请求报文:[" + data + "]");
this.result = this.response(httpURLConnection, encoding);
System.out.println("返回报文:[" + result + "]");
return httpURLConnection.getResponseCode();
} catch (Exception e) {
throw e;
}
}

/**
* 创建连接
*
* @return
* @throws ProtocolException
*/
private HttpURLConnection createConnectionByJSON(String encoding) throws ProtocolException {
HttpURLConnection httpURLConnection = null;
try {
if ("https".equalsIgnoreCase(url.getProtocol())) {
String urlStr = url.toString();
url = new URL(null, urlStr, new sun.net.www.protocol.https.Handler());//https请求用sun.net.www.protocol.https.Handler
httpURLConnection = (HttpURLConnection) url.openConnection();
} else {
httpURLConnection = (HttpURLConnection) url.openConnection();
}
} catch (IOException e) {
return null;
}
httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
httpURLConnection.setDoInput(true); // 可读
httpURLConnection.setDoOutput(true); // 可写
httpURLConnection.setUseCaches(false);// 取消缓存
httpURLConnection.setRequestProperty("Content-type",
"application/json;charset=" + encoding);
httpURLConnection.setRequestMethod("POST");
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情�?
return husn;
}
return httpURLConnection;
}

public static void main(String[] args) throws Exception{
Map<String,String> mapData = new HashMap<String,String>();
String encode = "utf-8";
//String url = "http://192.168.104.54:7002/NetPay/photoCompare.action";
// String url = "http://192.168.104.54:7002/NetPay/realNameCertify.action";
String url = "http://192.168.104.30:7002/NetPay/realNameCertify.action";
HttpClientTest client = new HttpClientTest(url, 60000, 60000);
//人脸识别
/* mapData.put("merchantId", "888888888888888");
mapData.put("merOrderNum", "20180125000003");
mapData.put("tranDateTime", "20180129100602");
mapData.put("name", "张单单");
mapData.put("IDNo", "371581199102104486");
File file = new File("F:/face/2.jpg");
InputStream is = new FileInputStream(file);
String base64 = Base64.encode(HttpClientTest.read(is));
mapData.put("photoImg", base64);
String txnString = mapData.get("merchantId") + "|" + mapData.get("merOrderNum") + "|" + mapData.get("tranDateTime") + "|" + mapData.get("name") + "|" + mapData.get("IDNo") + "|" + mapData.get("photoImg");
*/
//ACTNM=张单单&ACTNO=6217712504632908&AGENTTIME=20180404151140&CORG_NO=NETPAY&PhotoBase64=null&SIGN=c97c1d7ed0c4d9a53e1bb90ff2246610&TXNNO=000000000881236&VERTYPE=2&
//ACTNM=孙文超&ACTNO=6224110806792945&AGENTTIME=20180404151003&CORG_NO=NETPAY&PhotoBase64=null&SIGN=1466d1f649da47700c669f1bd2e27995&TXNNO=000000000881235&VERTYPE=2&
//银行账户认证
mapData.put("merchantId", "888888888888888");
mapData.put("merOrderNum", "000000000881235");
mapData.put("bussId", "100000");
mapData.put("tranDateTime", "20180404132956");
mapData.put("actNm", "此处为姓名加密后的密文");
mapData.put("actNm","hDoZECLTOGU1y3FMviSwgJkPHk7T5VnnUox3ZPwtSlv7YqwWZIrw4IVEPOHwWLqS1f9+4wPoWcGi85JzkKjwbW2SlD0T4Go7ukgXnWznS1O8bmVJ2GVAMXmw8VcJUczn+lH6Qsjn6OBhkkC5CkFlnIJjFEpTiLYwS0+PMw16xZ0E6jaimM4pN1UpwvSaWU5aQGHiV0jtS7BXKFpG+PjpAS+Z3WnqeP/nG1tN5SJimRg4tQlcOMrztqNO421ryAYx35tUvhLyRmQtup+oJmSGgYFIDY6HO2n5/PI0el1e47N8bXiWIFb6rOqhOv71sf1E4kEbGTEDNeUhWqnXkEKNpg==");
mapData.put("actNo", "此处为卡号加密后的密文");
mapData.put("actNo","LgWtrwGZk7kbZFlnQRNGN1j6hU2730OdttzQYwIcyw8odL5pZve9Uya44Yax/YJyNamawCkR5gIhCdCsdMaF90YBl3Tehrh2MuxL/+wFWR2ykpZeectq1AXE+MyJXpYYpaM2Ow0VBNDpMscYcwzR4GjMCCl8QSaM1y4vWQFD4S6g9ld/j4xwzK1mtte+YUlVUbTv9iwYWLCjJp+m9ICaZoh5eDmk3dTDsHcoKjQaI79sef1G00fftS0/WeYx6tMc8FI8ALOGaH2qtijVOHS7yB5YOME9b/tvS0hWR0yD48xgAXDo/Uqc+3RxgEAToEq4Rcr4kuRf8KSOzgwF/2TUdw==");
//mapData.put("actNo", "RcA6aSZ1H3oMi4ybKHOlhrQgFtmUpmbduHMEDASWE3yVzhMX4IfHer44+94Z+QJh5UW3JSRJXNEMFWc2hjbDh1abDohP4MwT/H5aZA/1iJ+sYpH945sQmpEyJVpQ1MhAz5xlXSall3M3MrLj492H+UyS8ctb5Jskwx5p0cBGJL7hoVUWvRejS7PCMZer75ch7PlhaQPZUbTpBaKrkIYuPJxvPSyNGOQEeF7mYLaR9gSZoG3CYbbNsuzOE4qnVFzoISvWHFFCjPfYvAtbtrw79EUaczE/n4VQWePVGnomqBeL/moYmmnXudk1Np5YFfnPK6WDyyt2HMoY7HaldnO6AA==");
//mapData.put("IDNo", "DaAurb7SSrN4Z8u5++zlJzdmr3HBDO4ZM0I++tp//HtOTvpPGrg/8QLMQQK+xwDlcSHSFuQfZWMGH0zNVnanyzcuR3FU2IoAxhV7VGzBeQ260eC8uQg1sotO6/FdQcvdR6kPxl43ykmbZXQSUideo48/aBhZuvc7teMsqLevTIX8MPPY3lbNCvGIn57O+V7pSJquh9kMoul/+mR0Tc6a1sHmwIn2h8tgHakyOUMvONNoQxOkxe2SwKtHXyYOFOulY2TewRbKB1RdKjLBeaevf5G7mEQTgwCXu4YEb483eR91LvzwCLETP0yz2fGqbccqaej/UXYqTxhbwjS7DXB00w==");
//mapData.put("IDNo", "");
//mapData.put("IDNo", "PIIVYETwwzwVfRGbFhKpRYdAXpyVpo25qe3NValTDtOz/xd/iMW9nSNy0XC9l6wIVirz/aA8az+X3+YIz9qhuuwaZDtWPSEs2SMg7Q9i0IMWMuXbsBPpA9xr4cJ2YDuMpMkshefU8WJRDvdlaShHaZpDkzlNbkJTDE2jD7g8mM6hFfQBB7gJRa7HQ9TTDRuYoaoWQctMhPRM6tJ5giXMdouCKeimgUmYGG7b0pKLpH2jaALNhFAQK90PlJXXK/bbnxS9pYG/O6G8G9XXXX6hd4sHvCVSVCFbL/ezhANg0clczBobYo9E0t/TUbAJcxC6f9C+5C35v3VfsPCZiNUNvw==");
//mapData.put("mobile", "");
String txnString = mapData.get("merchantId") + "|" + mapData.get("merOrderNum") + "|" + mapData.get("tranDateTime") + "|" + mapData.get("actNo") + "|" + mapData.get("actNm");
String signVal = MD5.getInstance().getMD5ofStr(txnString +"8EF53C251102A4E6");
mapData.put("signValue", signVal);
String jsonData = JSONArray.toJSONString(mapData);
client.sendByJson(jsonData, encode);
}
}

BaseHttpSSLSocketFactory类

/**
*
* Licensed Property to China UnionPay Co., Ltd.
*
* (C) Copyright of China UnionPay Co., Ltd. 2010
* All Rights Reserved.
*
*
* Modification History:
* =============================================================================
* Author Date Description
* ------------ ---------- ---------------------------------------------------
* xshu 2014-05-28 SSLSocket 閾炬帴宸ュ叿绫�(鐢ㄤ簬https)
* =============================================================================
*/
package com.ecton;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.X509Certificate;

public class BaseHttpSSLSocketFactory extends SSLSocketFactory {
private SSLContext getSSLContext() {
return createEasySSLContext();
}

@Override
public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2,
int arg3) throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

@Override
public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

@Override
public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}

@Override
public Socket createSocket(String arg0, int arg1) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}

@Override
public String[] getSupportedCipherSuites() {
// TODO Auto-generated method stub
return null;
}

@Override
public String[] getDefaultCipherSuites() {
// TODO Auto-generated method stub
return null;
}

@Override
public Socket createSocket(Socket arg0, String arg1, int arg2, boolean arg3)
throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

private SSLContext createEasySSLContext() {
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null,
new TrustManager[] { MyX509TrustManager.manger }, null);
return context;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static class MyX509TrustManager implements X509TrustManager {

static MyX509TrustManager manger = new MyX509TrustManager();

public MyX509TrustManager() {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] chain, String authType) {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}

/**
* 瑙e喅鐢变簬鏈嶅姟鍣ㄨ瘉涔﹂棶棰樺�鑷碒TTPS鏃犳硶璁块棶鐨勬儏鍐� PS:HTTPS hostname wrong: should be <localhost>
*/
public static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
// 鐩存帴杩斿洖true
return true;
}
}
}

原文地址:https://www.cnblogs.com/xint/p/9117245.html