看情况处理http和https的调用

//设置超时时间 10s
    static int timeout=10000;

    /**
     *看情况处理http和https的调用--get请求
     **/
    public static String doGetWithAuthorization(String url,String authorization){
        //临时变量
        String temp=url.substring(0,7).replace(" ","").toLowerCase();
        if(temp.indexOf("https")>-1){
            return doHttpsGetWithAuthorization(url,authorization);
        }else {
            return doHttpGetWithAuthorization(url,authorization);
        }
    }

    /**
     *看情况处理http和https的调用--post请求
     **/
    public static String doPostWithContentType(String url,String paramBody,String contentType){
        //临时变量
        String temp=url.substring(0,7).replace(" ","").toLowerCase();
        if(temp.indexOf("https")>-1){
            return doHttpsPostWithContentType(url,paramBody,contentType);
        }else {
            return doHttpPostWithContentType(url,paramBody,contentType);
        }
    }

    /**
     *https访问--post请求
     **/
    public static String doHttpsPostWithContentType(String url,String paramBody,String contentType){
        logger.info("Httpspost发送url:"+url+",请求参数:"+paramBody+",ContentType:"+contentType);
        //第一步:创建HttpClient对象
        CloseableHttpClient httpClient = createSSLClientDefault();
        String returnValue=null;
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第二步:创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //超时时间10秒,超时无响应会报错
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);

            //第三步:给httpPost设置参数及格式
            StringEntity requestEntity = new StringEntity(paramBody,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            //设置提交内容方式,如post提交 "application/json",或表单提交"application/x-www-form-urlencoded"
            httpPost.setHeader("Content-type", contentType);

            httpPost.setEntity(requestEntity);

            //第四步:发送HttpPost请求,获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler);
            logger.info("Httpspost接收url:"+url+",请求参数:"+paramBody+",返回值:"+returnValue);

        } catch(Exception e){
            e.printStackTrace();
            logger.info("Httpspost异常,url:"+url+",请求参数:"+paramBody+",异常信息:"+e.toString());
        } finally {
            close(httpClient);
        }
        //第五步:处理返回值
        return returnValue;
    }

    /**
     *http访问--post请求
     **/
    public static String doHttpPostWithContentType(String url,String paramBody,String contentType){
        logger.info("Httppost发送url:"+url+",请求参数:"+paramBody+",ContentType:"+contentType);
        CloseableHttpClient httpClient=null;
        String returnValue=null;

//        CloseableHttpResponse response = null;
        try{
            //第一步:创建HttpClient对象
            httpClient = HttpClients.createDefault();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            HttpPost httpPost = new HttpPost(url);

            //超时时间,超时无响应会报错
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);

            //第三步:给httpPost设置参数及格式
            StringEntity requestEntity = new StringEntity(paramBody,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            //设置提交内容方式,如post提交 "application/json",或表单提交"application/x-www-form-urlencoded"
            httpPost.setHeader("Content-type", contentType);
            httpPost.setEntity(requestEntity);

            //第四步:发送HttpPost请求,获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler);
            logger.info("Httppost接收url:"+url+",请求参数:"+paramBody+",ContentType:"+contentType+",返回值:"+returnValue);

        }catch (Exception e){
            e.printStackTrace();
            logger.info("Httppost异常,url:"+url+",请求参数:"+paramBody+",ContentType:"+contentType+",异常信息:"+e.toString());
        }finally {
            close(httpClient);
        }
        return returnValue;
    }

    /**
     * https访问--get请求
     **/
    public static String doHttpsGetWithAuthorization(String url,String authorization){
        logger.info("HttpsGet发送url:"+url);
        // 1. 创建带ssl的Httpclient对象
        CloseableHttpClient httpClient = createSSLClientDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String returnValue=null;
        try {
            // 2. 创建Http Get请求
            HttpGet httpGet = new HttpGet(url);

            //超时时间30秒,超时无响应会报错
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpGet.setConfig(requestConfig);

            //设置鉴权信息
            httpGet.setHeader("Authorization",authorization);
            returnValue = httpClient.execute(httpGet,responseHandler);
            logger.info("HttpsGet接收url:"+url+",返回值:"+returnValue);

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("HttpsGet异常,url:"+url+",异常信息:"+e.toString());
        } finally {
            close(httpClient);
        }

        return returnValue;
    }

    /**
     * http访问--get请求
     **/
    public static String doHttpGetWithAuthorization(String url,String authorization){
        logger.info("HttpGet发送url:"+url);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String returnValue=null;
        CloseableHttpResponse response = null;
        try {
            // 2. 创建Http Get请求
            HttpGet httpGet = new HttpGet(url);

            //超时时间,超时无响应会报错
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpGet.setConfig(requestConfig);

            //设置鉴权信息
            httpGet.setHeader("Authorization",authorization);
            
            // 3. 执行http请求
            returnValue = httpClient.execute(httpGet,responseHandler);
            logger.info("HttpGet接收url:"+url+",返回值:"+returnValue);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("HttpGet异常,url:"+url+",返回值:"+returnValue+",异常信息:"+e.toString());
        } finally {
            close(httpClient);
        }
        return returnValue;
    }

    /**
     *SSL身份认证
     **/
    public static CloseableHttpClient createSSLClientDefault() {
        CloseableHttpClient closeableHttpClient;
        try {
            SSLContext sslContext = new org.apache.http.ssl.SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            closeableHttpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            logger.info("SSLHttpClient创建成功");
            return closeableHttpClient;
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(CloseableHttpClient httpClient){
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("http关闭异常");
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值