java使用自定义SSL工具类执行Https的网络请求
package cn.com.baidu.send.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* SendShortMessage
*/
public class SendShortMessage {
public static void send(String mobile, String content, String sign) {
try {
SSLClient httpclient = new SSLClient();
HttpPost post = new HttpPost(HOST);
post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("action", "send"));
nvps.add(new BasicNameValuePair("userid", ""));
nvps.add(new BasicNameValuePair("mobile", mobile));
nvps.add(new BasicNameValuePair("sendTime", DateUtil.getTime()));
post.setEntity(new UrlEncodedFormEntity(nvps, CHARSET));
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
// 将字符转化为XML
String returnString = EntityUtils.toString(entity, "UTF-8");
// 进行业务判断
EntityUtils.consume(entity);
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.com.baidu.send.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* SSLClient
*/
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
|