下面的代码均是测试OK的,商用请注意。
Android
看代码
public static String getHttpsContent(String url) {
String str2 = "";
try {
HttpClient a = getHttpClient();
HttpUriRequest httpGet = new HttpGet(url.replace(" ", ""));
// httpGet.setHeader("User-Agent", "");
HttpResponse execute = a.execute(httpGet);
if (execute.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(execute.getEntity());
}
return "error";
} catch (Exception e) {
e.printStackTrace();
return str2;
}
}
public static HttpClient getHttpClient() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 8443));
HttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(basicHttpParams, u);
HttpConnectionParams.setSoTimeout(basicHttpParams, u);
return new DefaultHttpClient(new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry), basicHttpParams);
}
gradle中需要设置
useLibrary 'org.apache.http.legacy'
Java SE
下面这个代码是抄的别人的,只是用于实验。
public static String sendXMLDataByGet(String url, String xml) {
// 创建HttpClient实例
if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
StringBuilder urlString = new StringBuilder();
urlString.append(url);
if(xml != null){
urlString.append("?");
System.out.println("getUTF8XMLString(xml):" + getUTF8XMLString(xml));
try {
urlString.append(URLEncoder.encode(getUTF8XMLString(xml), "UTF-8"));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
}
String urlReq = urlString.toString();
// 创建Get方法实例
HttpGet httpsgets = new HttpGet(urlReq);
// httpsgets.addHeader("Cookie", "");
String strRep = "";
try {
HttpResponse response = client.execute(httpsgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
strRep = EntityUtils.toString(response.getEntity());
// Do not need the rest
httpsgets.abort();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strRep;
}
/**
* 访问https的网站
*
* @param httpclient
*/
private static void enableSSL(DefaultHttpClient httpclient) {
//调用ssl
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{truseAllManager}, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
} catch (Exception e) {
e.printStackTrace();
}
}
// test url
public static void main(String[] args) {
String urlString = "https://www.xxx.com:8443/Q?Info=All";
String output = new String(sendXMLDataByGet(urlString.replace(" ", ""),null));
System.out.println(output);
}