import org.apache.log4j.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.*;
import java.util.Map;
/**
* 描述:HTTPS接口调用工具 <br>
* 日期:2017-4-26 <br>
*/
public class HttpClient {
private static final Logger log = Logger.getLogger(HttpClient.class);
private URL url;
private int connectionTimeout;
private int readTimeOut;
private String result;
public String getResult() {
return this.result;
}
public void setResult(String result) {
this.result = result;
}
public HttpClient(String url, int connectionTimeout, int readTimeOut) {
try {
this.url = new URL(url);
this.connectionTimeout = connectionTimeout;
this.readTimeOut = readTimeOut;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 功能:调用接口<br>
* 作者:zhq<br>
* 日期:2017-4-26<br>
* @param data
* @param encoding
* @return
* 修改:<br>
*/
public int send(Map<String, String> data, String encoding) throws Exception {
try {
HttpURLConnection httpURLConnection = createConnection(encoding);
if (null == httpURLConnection) {
throw new Exception("创建联接失败");
}
requestServer(httpURLConnection, getRequestParamString(data, encoding), encoding);
this.result = response(httpURLConnection, encoding);
return httpURLConnection.getResponseCode();
} catch (Exception e) {
throw e;
}
}
private void requestServer(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();
if (null != out)
out.close();
} catch (Exception e) {
throw e;
} finally {
if (null != out)
out.close();
}
}
private String response(HttpURLConnection connection, String encoding) throws URISyntaxException, IOException, Exception {
InputStream in = null;
StringBuilder sb = new StringBuilder(1024);
BufferedReader br = null;
String temp = null;
try {
if (200 == connection.getResponseCode()) {
in = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, encoding));
while (null != (temp = br.readLine())) {
sb.append(temp);
}
} else {
try {
in = connection.getErrorStream();
br = new BufferedReader(new InputStreamReader(in, encoding));
while (null != (temp = br.readLine())) {
sb.append(temp);
}
} catch(Exception e){
log.error("处理报错信息异常", e);
}
}
String str1 = sb.toString();
return str1;
} catch (Exception e) {
throw e;
} finally {
if (null != br) {
br.close();
}
if (null != in) {
in.close();
}
if (null != connection)
connection.disconnect();
}
}
private HttpURLConnection createConnection(String encoding) throws ProtocolException {
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) this.url.openConnection();
} catch (IOException e) {
e.printStackTrace();
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;
// //是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false
//// if(!SDKConfig.getConfig().isIfValidateRemoteCert()){
// husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
// husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况
//// }
// return husn;
// }
if ("https".equalsIgnoreCase(this.url.getProtocol())) {
HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
husn.setSSLSocketFactory(new com.unionpay.mpi.BaseHttpSSLSocketFactory());
husn.setHostnameVerifier(new com.unionpay.mpi.BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier(){
@Override
public boolean verify(String hostname, SSLSession session) {
return false;
}
});
return husn;
}
// httpURLConnection.setRequestProperty("Content-type", new StringBuilder().append("application/json;charset=").append(encoding).toString());
// if ("https".equalsIgnoreCase(this.url.getProtocol())) {
// HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
// husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
// husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());
// return husn;
// }
// httpURLConnection.setRequestProperty("Content-type",
// "application/x-www-form-urlencoded;charset=" + encoding);
// httpURLConnection.setRequestMethod("GET");
return httpURLConnection;
}
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 (Map.Entry en : requestParam.entrySet()) {
try {
sf.append(new StringBuilder().append((String)en.getKey()).append("=").append((null == en.getValue()) || ("".equals(en.getValue())) ? "" : URLEncoder.encode((String)en.getValue(), coder)).append("&").toString());
}
catch (Exception e)
{
e.printStackTrace();
return "";
}
}
reqstr = sf.substring(0, sf.length() - 1);
}
return reqstr;
}
}