Skip to content

Instantly share code, notes, and snippets.

@malinkang
Created January 10, 2014 08:20
Show Gist options
  • Save malinkang/8348531 to your computer and use it in GitHub Desktop.
Save malinkang/8348531 to your computer and use it in GitHub Desktop.
public class SSLSocketFactoryEx extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port,
autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
public class HttpRequest {
/**
* get请求
*
* @param urlString
* @param params
* @return
*/
public static String getRequest(String urlString, Map<String, String> params) {
try {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(urlString);
if (null != params) {
urlBuilder.append("?");
Iterator<Entry<String, String>> iterator = params.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
urlBuilder
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append('=')
.append(URLEncoder.encode(param.getValue(), "UTF-8"));
if (iterator.hasNext()) {
urlBuilder.append('&');
}
}
}
// 创建HttpClient对象
HttpClient client = getNewHttpClient();
// 发送get请求创建HttpGet对象
HttpGet getMethod = new HttpGet(urlBuilder.toString());
HttpResponse response = client.execute(getMethod);
// 获取状态码
int res = response.getStatusLine().getStatusCode();
if (res == 200) {
StringBuilder builder = new StringBuilder();
// 获取响应内容
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader
.readLine()) {
builder.append(s);
}
return builder.toString();
} else {
// 处理错误码
}
} catch (Exception e) {
}
return null;
}
/**
* post请求
*
* @param urlString
* @param params
* @return
*/
public static String postRequest(String urlString,
List<BasicNameValuePair> params) {
try {
// 1. 创建HttpClient对象
HttpClient client = getNewHttpClient();
// 2. 发get请求创建HttpGet对象
HttpPost postMethod = new HttpPost(urlString);
postMethod.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = client.execute(postMethod);
int statueCode = response.getStatusLine().getStatusCode();
if (statueCode == 200) {
System.out.println(statueCode);
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}
return null;
}
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment