• 使用httpClient发送请求(支持https)


    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.6'
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    /**
     * Created by roger on 2019/9/11.
     */
    public class SSLUtils {
    
        private static TrustManager[] trustAllHttpsCertificates() throws KeyManagementException {
    
            TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }
    
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
            }};
            return trustManagers;
        }
    
    
        public static CloseableHttpClient createHttpClientSSL() throws NoSuchAlgorithmException, KeyManagementException {
    
            CloseableHttpClient httpClient = null;
            TrustManager[] trustManagers = trustAllHttpsCertificates();
            SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.SSL);
            sslContext.init(null, trustManagers, new SecureRandom());
            httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).build();
    
            return httpClient;
        }
    
        public static CloseableHttpClient createHttpClientTLS() throws NoSuchAlgorithmException, KeyManagementException {
            CloseableHttpClient httpClient = null;
            TrustManager[] trustManagers = trustAllHttpsCertificates();
            SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            return httpClient;
        }
    
        public static SSLSocketFactory createSSLSocketFactory() throws Exception {
            TrustManager[] trustManagers = trustAllHttpsCertificates();
            SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            SSLSocketFactory factory = sslContext.getSocketFactory();
            return factory;
        }
    }
    

      

    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.*;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Set;
    
    /**
     * http/https 请求类
     *
     * @Author: alex
     * @Date: 2020/03/08
     */
    public class RestUtil {
    
        /**
         * GET请求,获取JSONObject信息
         *
         * @param url
         * @return JSONObject
         * @throws Exception
         */
        public static JSONObject getByHttps(String url) throws Exception {
            CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
            try {
                // 创建httpget.
                HttpGet httpget = new HttpGet(url);
                // 执行get请求.
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 获取响应实体
                    return covertEntityToJSON(response.getEntity());
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        public static JSONObject getByHttp(String url) throws Exception {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                // 创建httpget.
                HttpGet httpget = new HttpGet(url);
                // 执行get请求.
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 获取响应实体
                    return covertEntityToJSON(response.getEntity());
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        public static String getStringByHttps(String url) throws Exception {
            CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
            try {
                // 创建httpget.
                HttpGet httpget = new HttpGet(url);
                // 执行get请求.
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 获取响应实体
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String res = EntityUtils.toString(entity, "UTF-8");
                        return res;
                    } else {
                        return null;
                    }
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        public static String getStringByHttps(String url, String cookie) throws Exception {
            CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
            try {
                // 创建httpget.
                HttpGet httpget = new HttpGet(url);
                httpget.addHeader("Cookie", cookie);
                // 执行get请求.
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 获取响应实体
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String res = EntityUtils.toString(entity, "UTF-8");
                        return res;
                    } else {
                        return null;
                    }
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * GET请求,获取byte数组信息
         *
         * @param url
         * @return byte[]
         * @throws Exception
         */
        public static byte[] getBinaryByHttps(String url) throws Exception {
            CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
            try {
                // 创建httpget.
                HttpGet httpget = new HttpGet(url);
                // 执行get请求.
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 获取响应实体
                    return covertEntityToBinary(response.getEntity());
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * POST请求 HTTP
         *
         * @param url
         * @param parameters
         * @return
         * @throws Exception
         */
        public static JSONObject postHttp(String url, JSONObject parameters) throws Exception {
            // 创建默认的httpClient实例.
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            StringEntity s = new StringEntity(parameters.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(s);
            HttpResponse res = httpclient.execute(httpPost);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity(), "UTF-8");// 返回json格式:
                JSONObject jsonObject = JSONObject.parseObject(result);
                return jsonObject;
            }
            return null;
        }
    
        public static String postHttpForm(String url, JSONObject parameters, String cookie) {
            // 创建默认的httpClient实例.
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Cookie", cookie);
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            Set<String> keySet = parameters.keySet();
            for (String key : keySet) {
                String value = parameters.get(key).toString();
                if (value.equals("null") != true) {
                    nameValuePairs.add(new BasicNameValuePair(key, value));
                }
            }
            UrlEncodedFormEntity uefEntity;
            try {
                uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
                httpPost.setEntity(uefEntity);
                CloseableHttpResponse response = httpclient.execute(httpPost);
                try {
                    String res = EntityUtils.toString(response.getEntity(), "UTF-8");
                    return res;
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * POST请求 HTTPS
         *
         * @param url
         * @param parameters
         * @return JSONObject
         * @throws Exception
         */
        public static JSONObject postHttps(String url, JSONObject parameters) throws Exception {
            // 创建默认的httpClient实例.
            CloseableHttpClient httpClient = SSLUtils.createHttpClientTLS();
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            // 创建参数队列
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            Set<String> keySet = parameters.keySet();
            for (String key : keySet) {
                String value = parameters.get(key).toString();
                if (value.equals("null") != true) {
                    nameValuePairs.add(new BasicNameValuePair(key, value));
                }
            }
            return executeSendRequest(httpClient,httpPost,nameValuePairs);
        }
    
        /**
         * 执行发送请求
         * @param httpclient
         * @param httpPost
         * @param nameValuePairs
         * @return JSONObject
         * @throws Exception
         */
        private static JSONObject executeSendRequest(CloseableHttpClient httpclient, HttpPost httpPost, List<NameValuePair> nameValuePairs) throws Exception {
            UrlEncodedFormEntity uefEntity;
            try {
                uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
                httpPost.setEntity(uefEntity);
                CloseableHttpResponse response = httpclient.execute(httpPost);
                try {
                    return covertEntityToJSON(response.getEntity());
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * 将HttpEntity转换成JSONObject
         *
         * @param entity
         * @return JSONObject
         * @throws Exception
         */
        private static JSONObject covertEntityToJSON(HttpEntity entity) throws Exception {
            if (entity != null) {
                String res = EntityUtils.toString(entity, "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(res);
                return jsonObject;
            } else {
                return null;
            }
        }
    
        /**
         * 将HttpEntity转换成byte[]
         *
         * @param entity
         * @return byte[]
         * @throws Exception
         */
        private static byte[] covertEntityToBinary(HttpEntity entity) throws Exception {
            if (entity != null) {
                byte[] res = EntityUtils.toByteArray(entity);
                return res;
            } else {
                return null;
            }
        }
    
        public static void main(String[] args) throws Exception {
    
        }
    }
    

      

  • 相关阅读:
    iOS中Block介绍(一)基础
    iOS消息推送机制的实现
    iOS AvPlayer AvAudioPlayer音频的后台播放问题
    git 解决fatal: Not a git repository
    执行git命令出现 xcrun: error:
    ios UIView的clipsTobounds属性
    UIWindow的层级问题Level
    解决方案:The file * couldn't be opened because you don't have permission to view it
    NSString 中包含中文字符时转换为NSURL
    UIView动画
  • 原文地址:https://www.cnblogs.com/james-roger/p/15209090.html
Copyright © 2020-2023  润新知