Java Https请求工具类
生活随笔
收集整理的這篇文章主要介紹了
Java Https请求工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
個人技術網站?歡迎關注
由于微信API接口建議使用Https請求方式 而且過不久就廢棄http請求方式了 所以提供以下Https工具類
?
public class SSLClient extends DefaultHttpClient{public SSLClient() throws Exception{super();SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {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));} }
https請求工具類
?
?
public class HttpClientUtil {/*** 發送post請求* @param url* @param map* @param charset* @return*/public static String doPost(String url,Map<String,String> map,String charset){HttpClient httpClient = null;HttpPost httpPost = null;String result = null;try{httpClient = new SSLClient();httpPost = new HttpPost(url);//設置參數List<NameValuePair> list = new ArrayList<NameValuePair>();Iterator iterator = map.entrySet().iterator();while(iterator.hasNext()){Entry<String,String> elem = (Entry<String, String>) iterator.next();list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));}if(list.size() > 0){UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);httpPost.setEntity(entity);}HttpResponse response = httpClient.execute(httpPost);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}/*** 發送get請求* @param url 鏈接地址* @param charset 字符編碼,若為null則默認utf-8* @return*/public static String doGet(String url,String charset){if(null == charset){charset = "utf-8";}HttpClient httpClient = null;HttpGet httpGet= null;String result = null;try {httpClient = new SSLClient();httpGet = new HttpGet(url);HttpResponse response = httpClient.execute(httpGet);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}} catch (Exception e) {e.printStackTrace();}return result;}}
本工具類根據http://blog.csdn.net/rongyongfeikai2/article/details/41659353/進行了小改
?
總結
以上是生活随笔為你收集整理的Java Https请求工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 客户拜访
- 下一篇: 花花收纳app-个人物品收纳管理记录软件