https http请求 demo

package com.jiedaibao.umg.test.provider;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.commons.lang.StringUtils;


public class TestHttp {
public static void main(String[] args) throws IOException {
String strUrl="http://127.0.0.1:8012/umg/service/user/userRegister?a=1&b=2";
String charset ="utf-8";
Map<String,String> hashMap = new HashMap<String,String>();
byte[]  bytes=null;


StringBuffer sb = new StringBuffer();
// 1.转换map成string
Set<Entry<String, String>> entrySet = hashMap.entrySet();
for (Entry<String, String> entry : entrySet) {
String value = entry.getValue();
String key = entry.getKey();
if(!StringUtils.isEmpty(value)){
sb.append(key).append("=").append(value).append("&");
}
}
String stringMap = sb.toString();
String substring = stringMap.substring(0,stringMap.length()-1);
if(!StringUtils.isEmpty(substring)){
try {
bytes = substring.getBytes(charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// ========================================================
HttpsURLConnection conn =null;
URL url =null;
SSLContext ssl =null;
if(url.getProtocol().equals("https")){
try {
// 2.创建请求的url对象
url = new URL(strUrl);
// 3.相关协议对象
ssl =SSLContext.getInstance("TLS");
ssl.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
// 4.获取对象,将协议内容添加,
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssl.getSocketFactory());
conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
// 如果不是https请求 直接获取连接
conn =(HttpsURLConnection) url.openConnection();
}
conn.setRequestMethod("post");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");//接收类型
conn.setRequestProperty("User-Agent", "top-sdk-java");//代理
conn.setRequestProperty("Content-Type", charset);//文本类型
//如果 有其他类型的可以通过map来传输 property
Map<String,String> hashMap2 = new HashMap<String,String>();
Set<Entry<String, String>> entrySet2 = hashMap2.entrySet();
if(hashMap != null){
for (Entry<String, String> entry :entrySet2) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setReadTimeout(1000);
conn.setConnectTimeout(1000);
// =======================================================
// 5.写流
OutputStream outputStream = conn.getOutputStream();
outputStream.write(bytes);
// 6.读流
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
StringBuffer s =new StringBuffer();
char[] c =new char[1024];
int read =0;
while((read = inputStreamReader.read(c))>0){
s.append(c ,0 ,read);
}
s.toString();
// 7.关闭流
if(outputStream!=null)outputStream.close();
}


//实现X509TrustManager 接口
private static class DefaultTrustManager implements X509TrustManager {


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


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


public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
// 获取URL 路径对象
private static URL getURL(String stringUrl ,String query) throws MalformedURLException {
URL url = new URL(stringUrl);

if(StringUtils.isEmpty(query)){
return url;
}
if(StringUtils.isEmpty(url.getQuery())){
if(stringUrl.endsWith("?")){
stringUrl =stringUrl+query;
}else{
stringUrl=stringUrl+"?"+query;
}

}else{
if(stringUrl.endsWith("&")){
stringUrl=stringUrl+query;
}else{
stringUrl=stringUrl+"&"+query;
}
}
return new URL(stringUrl);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值