zoukankan      html  css  js  c++  java
  • JAVA HTTP请求和HTTPS请求

    HTTP与HTTPS区别:http://blog.csdn.net/lyhjava/article/details/51860215

    URL发送 HTTP、HTTPS:http://blog.csdn.net/guozili1/article/details/53995121

    HttpClient 发送 HTTP、HTTPS 请求的简单封装

    http://blog.csdn.net/happylee6688/article/details/47148227

      1 <span style="font-family:Comic Sans MS;">import org.apache.commons.io.IOUtils;
      2 import org.apache.http.HttpEntity;
      3 import org.apache.http.HttpResponse;
      4 import org.apache.http.HttpStatus;
      5 import org.apache.http.NameValuePair;
      6 import org.apache.http.client.HttpClient;
      7 import org.apache.http.client.config.RequestConfig;
      8 import org.apache.http.client.entity.UrlEncodedFormEntity;
      9 import org.apache.http.client.methods.CloseableHttpResponse;
     10 import org.apache.http.client.methods.HttpGet;
     11 import org.apache.http.client.methods.HttpPost;
     12 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
     13 import org.apache.http.conn.ssl.SSLContextBuilder;
     14 import org.apache.http.conn.ssl.TrustStrategy;
     15 import org.apache.http.conn.ssl.X509HostnameVerifier;
     16 import org.apache.http.entity.StringEntity;
     17 import org.apache.http.impl.client.CloseableHttpClient;
     18 import org.apache.http.impl.client.DefaultHttpClient;
     19 import org.apache.http.impl.client.HttpClients;
     20 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
     21 import org.apache.http.message.BasicNameValuePair;
     22 import org.apache.http.util.EntityUtils;
     23 
     24 import javax.net.ssl.SSLContext;
     25 import javax.net.ssl.SSLException;
     26 import javax.net.ssl.SSLSession;
     27 import javax.net.ssl.SSLSocket;
     28 import java.io.IOException;
     29 import java.io.InputStream;
     30 import java.nio.charset.Charset;
     31 import java.security.GeneralSecurityException;
     32 import java.security.cert.CertificateException;
     33 import java.security.cert.X509Certificate;
     34 import java.util.ArrayList;
     35 import java.util.HashMap;
     36 import java.util.List;
     37 import java.util.Map;
     38 
     39 /**
     40  * HTTP 请求工具类
     41  *
     42  * @author : liii
     43  * @version : 1.0.0
     44  * @date : 2015/7/21
     45  * @see : TODO
     46  */
     47 public class HttpUtil {
     48     private static PoolingHttpClientConnectionManager connMgr;
     49     private static RequestConfig requestConfig;
     50     private static final int MAX_TIMEOUT = 7000;
     51 
     52     static {
     53         // 设置连接池
     54         connMgr = new PoolingHttpClientConnectionManager();
     55         // 设置连接池大小
     56         connMgr.setMaxTotal(100);
     57         connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
     58 
     59         RequestConfig.Builder configBuilder = RequestConfig.custom();
     60         // 设置连接超时
     61         configBuilder.setConnectTimeout(MAX_TIMEOUT);
     62         // 设置读取超时
     63         configBuilder.setSocketTimeout(MAX_TIMEOUT);
     64         // 设置从连接池获取连接实例的超时
     65         configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
     66         // 在提交请求之前 测试连接是否可用
     67         configBuilder.setStaleConnectionCheckEnabled(true);
     68         requestConfig = configBuilder.build();
     69     }
     70 
     71     /**
     72      * 发送 GET 请求(HTTP),不带输入数据
     73      * @param url
     74      * @return
     75      */
     76     public static String doGet(String url) {
     77         return doGet(url, new HashMap<String, Object>());
     78     }
     79 
     80     /**
     81      * 发送 GET 请求(HTTP),K-V形式
     82      * @param url
     83      * @param params
     84      * @return
     85      */
     86     public static String doGet(String url, Map<String, Object> params) {
     87         String apiUrl = url;
     88         StringBuffer param = new StringBuffer();
     89         int i = 0;
     90         for (String key : params.keySet()) {
     91             if (i == 0)
     92                 param.append("?");
     93             else
     94                 param.append("&");
     95             param.append(key).append("=").append(params.get(key));
     96             i++;
     97         }
     98         apiUrl += param;
     99         String result = null;
    100         HttpClient httpclient = new DefaultHttpClient();
    101         try {
    102             HttpGet httpPost = new HttpGet(apiUrl);
    103             HttpResponse response = httpclient.execute(httpPost);
    104             int statusCode = response.getStatusLine().getStatusCode();
    105 
    106             System.out.println("执行状态码 : " + statusCode);
    107 
    108             HttpEntity entity = response.getEntity();
    109             if (entity != null) {
    110                 InputStream instream = entity.getContent();
    111                 result = IOUtils.toString(instream, "UTF-8");
    112             }
    113         } catch (IOException e) {
    114             e.printStackTrace();
    115         }
    116         return result;
    117     }
    118 
    119     /**
    120      * 发送 POST 请求(HTTP),不带输入数据
    121      * @param apiUrl
    122      * @return
    123      */
    124     public static String doPost(String apiUrl) {
    125         return doPost(apiUrl, new HashMap<String, Object>());
    126     }
    127 
    128     /**
    129      * 发送 POST 请求(HTTP),K-V形式
    130      * @param apiUrl API接口URL
    131      * @param params 参数map
    132      * @return
    133      */
    134     public static String doPost(String apiUrl, Map<String, Object> params) {
    135         CloseableHttpClient httpClient = HttpClients.createDefault();
    136         String httpStr = null;
    137         HttpPost httpPost = new HttpPost(apiUrl);
    138         CloseableHttpResponse response = null;
    139 
    140         try {
    141             httpPost.setConfig(requestConfig);
    142             List<NameValuePair> pairList = new ArrayList<>(params.size());
    143             for (Map.Entry<String, Object> entry : params.entrySet()) {
    144                 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
    145                         .getValue().toString());
    146                 pairList.add(pair);
    147             }
    148             httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
    149             response = httpClient.execute(httpPost);
    150             System.out.println(response.toString());
    151             HttpEntity entity = response.getEntity();
    152             httpStr = EntityUtils.toString(entity, "UTF-8");
    153         } catch (IOException e) {
    154             e.printStackTrace();
    155         } finally {
    156             if (response != null) {
    157                 try {
    158                     EntityUtils.consume(response.getEntity());
    159                 } catch (IOException e) {
    160                     e.printStackTrace();
    161                 }
    162             }
    163         }
    164         return httpStr;
    165     }
    166 
    167     /**
    168      * 发送 POST 请求(HTTP),JSON形式
    169      * @param apiUrl
    170      * @param json json对象
    171      * @return
    172      */
    173     public static String doPost(String apiUrl, Object json) {
    174         CloseableHttpClient httpClient = HttpClients.createDefault();
    175         String httpStr = null;
    176         HttpPost httpPost = new HttpPost(apiUrl);
    177         CloseableHttpResponse response = null;
    178 
    179         try {
    180             httpPost.setConfig(requestConfig);
    181             StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
    182             stringEntity.setContentEncoding("UTF-8");
    183             stringEntity.setContentType("application/json");
    184             httpPost.setEntity(stringEntity);
    185             response = httpClient.execute(httpPost);
    186             HttpEntity entity = response.getEntity();
    187             System.out.println(response.getStatusLine().getStatusCode());
    188             httpStr = EntityUtils.toString(entity, "UTF-8");
    189         } catch (IOException e) {
    190             e.printStackTrace();
    191         } finally {
    192             if (response != null) {
    193                 try {
    194                     EntityUtils.consume(response.getEntity());
    195                 } catch (IOException e) {
    196                     e.printStackTrace();
    197                 }
    198             }
    199         }
    200         return httpStr;
    201     }
    202 
    203     /**
    204      * 发送 SSL POST 请求(HTTPS),K-V形式
    205      * @param apiUrl API接口URL
    206      * @param params 参数map
    207      * @return
    208      */
    209     public static String doPostSSL(String apiUrl, Map<String, Object> params) {
    210         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    211         HttpPost httpPost = new HttpPost(apiUrl);
    212         CloseableHttpResponse response = null;
    213         String httpStr = null;
    214 
    215         try {
    216             httpPost.setConfig(requestConfig);
    217             List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
    218             for (Map.Entry<String, Object> entry : params.entrySet()) {
    219                 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
    220                         .getValue().toString());
    221                 pairList.add(pair);
    222             }
    223             httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
    224             response = httpClient.execute(httpPost);
    225             int statusCode = response.getStatusLine().getStatusCode();
    226             if (statusCode != HttpStatus.SC_OK) {
    227                 return null;
    228             }
    229             HttpEntity entity = response.getEntity();
    230             if (entity == null) {
    231                 return null;
    232             }
    233             httpStr = EntityUtils.toString(entity, "utf-8");
    234         } catch (Exception e) {
    235             e.printStackTrace();
    236         } finally {
    237             if (response != null) {
    238                 try {
    239                     EntityUtils.consume(response.getEntity());
    240                 } catch (IOException e) {
    241                     e.printStackTrace();
    242                 }
    243             }
    244         }
    245         return httpStr;
    246     }
    247 
    248     /**
    249      * 发送 SSL POST 请求(HTTPS),JSON形式
    250      * @param apiUrl API接口URL
    251      * @param json JSON对象
    252      * @return
    253      */
    254     public static String doPostSSL(String apiUrl, Object json) {
    255         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    256         HttpPost httpPost = new HttpPost(apiUrl);
    257         CloseableHttpResponse response = null;
    258         String httpStr = null;
    259 
    260         try {
    261             httpPost.setConfig(requestConfig);
    262             StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
    263             stringEntity.setContentEncoding("UTF-8");
    264             stringEntity.setContentType("application/json");
    265             httpPost.setEntity(stringEntity);
    266             response = httpClient.execute(httpPost);
    267             int statusCode = response.getStatusLine().getStatusCode();
    268             if (statusCode != HttpStatus.SC_OK) {
    269                 return null;
    270             }
    271             HttpEntity entity = response.getEntity();
    272             if (entity == null) {
    273                 return null;
    274             }
    275             httpStr = EntityUtils.toString(entity, "utf-8");
    276         } catch (Exception e) {
    277             e.printStackTrace();
    278         } finally {
    279             if (response != null) {
    280                 try {
    281                     EntityUtils.consume(response.getEntity());
    282                 } catch (IOException e) {
    283                     e.printStackTrace();
    284                 }
    285             }
    286         }
    287         return httpStr;
    288     }
    289 
    290     /**
    291      * 创建SSL安全连接
    292      *
    293      * @return
    294      */
    295     private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
    296         SSLConnectionSocketFactory sslsf = null;
    297         try {
    298             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    299 
    300                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    301                     return true;
    302                 }
    303             }).build();
    304             sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
    305 
    306                 @Override
    307                 public boolean verify(String arg0, SSLSession arg1) {
    308                     return true;
    309                 }
    310 
    311                 @Override
    312                 public void verify(String host, SSLSocket ssl) throws IOException {
    313                 }
    314 
    315                 @Override
    316                 public void verify(String host, X509Certificate cert) throws SSLException {
    317                 }
    318 
    319                 @Override
    320                 public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
    321                 }
    322             });
    323         } catch (GeneralSecurityException e) {
    324             e.printStackTrace();
    325         }
    326         return sslsf;
    327     }
    328 
    329 
    330     /**
    331      * 测试方法
    332      * @param args
    333      */
    334     public static void main(String[] args) throws Exception {
    335 
    336     }
    337 }</span>

    显示

  • 相关阅读:
    spark 1.1.0 单机与yarn部署
    hadoop 2.5.1单机安装部署伪集群
    perl C/C++ 扩展(五)
    perl C/C++ 扩展(一)
    perl C/C++ 扩展(二)
    perl C/C++ 扩展(三)
    perl C/C++ 扩展(四)
    SpiderMonkey 入门学习(一)
    新装centos 6.5 基本配置
    Linux(16):Shell编程(3)
  • 原文地址:https://www.cnblogs.com/wangleBlogs/p/8135571.html
Copyright © 2011-2022 走看看