1、https请求发送-工具类

  1. 1、利用HttpClient进行post请求的工具类
  2. /**
  3. * 利用HttpClient进行post请求的工具类
  4. */
  5. public class HttpClientUtil {
  6. public static String doGet(String url,String charset){
  7. HttpClient httpClient;
  8. HttpGet httpGet;
  9. String result = null;
  10. try{
  11. httpClient = new SSLClient();
  12. httpGet = new HttpGet(url);
  13. //设置参数
  14. HttpResponse response = httpClient.execute(httpGet);
  15. if(response != null){
  16. HttpEntity resEntity = response.getEntity();
  17. if(resEntity != null){
  18. result = EntityUtils.toString(resEntity,charset);
  19. }
  20. }
  21. }catch(Exception ex){
  22. ex.printStackTrace();
  23. }
  24. return result;
  25. }
  26. public String doPost(String url,Map<String,String> map,String charset){
  27. HttpClient httpClient = null;
  28. HttpPost httpPost = null;
  29. String result = null;
  30. try{
  31. httpClient = new SSLClient();
  32. httpPost = new HttpPost(url);
  33. //设置参数
  34. List<NameValuePair> list = new ArrayList<NameValuePair>();
  35. Iterator iterator = map.entrySet().iterator();
  36. while(iterator.hasNext()){
  37. Entry<String,String> elem = (Entry<String, String>) iterator.next();
  38. list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
  39. }
  40. if(list.size() > 0){
  41. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
  42. httpPost.setEntity(entity);
  43. }
  44. HttpResponse response = httpClient.execute(httpPost);
  45. if(response != null){
  46. HttpEntity resEntity = response.getEntity();
  47. if(resEntity != null){
  48. result = EntityUtils.toString(resEntity,charset);
  49. }
  50. }
  51. }catch(Exception ex){
  52. ex.printStackTrace();
  53. }
  54. return result;
  55. }
  56. }
  57. 2、用于进行Https请求的HttpClient
  58. //用于进行Https请求的HttpClient
  59. public class SSLClient extends DefaultHttpClient{
  60. public SSLClient() throws Exception{
  61. super();
  62. SSLContext ctx = SSLContext.getInstance("TLS");
  63. X509TrustManager tm = new X509TrustManager() {
  64. @Override
  65. public void checkClientTrusted(X509Certificate[] chain,
  66. String authType) throws CertificateException {
  67. }
  68. @Override
  69. public void checkServerTrusted(X509Certificate[] chain,
  70. String authType) throws CertificateException {
  71. }
  72. @Override
  73. public X509Certificate[] getAcceptedIssuers() {
  74. return null;
  75. }
  76. };
  77. ctx.init(null, new TrustManager[]{tm}, null);
  78. SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  79. ClientConnectionManager ccm = this.getConnectionManager();
  80. SchemeRegistry sr = ccm.getSchemeRegistry();
  81. sr.register(new Scheme("https", 443, ssf));
  82. }
  83. }