网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Http、Https请求工具类-创新互联

1. maven引入httpclient依赖
  org.apache.httpcomponents   httpclient  4.5.12
2. GET请求
public static String doGet(String path, Mapparam, Mapheaders) {
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = wrapClient(path);
    // 创建uri
    URIBuilder builder = null;
    try {
        builder = new URIBuilder(path);
        if (param != null) {
            for (String key : param.keySet()) {
                builder.addParameter(key, param.get(key));
            }
        }
        URI uri = builder.build();
        // 创建http GET请求
        httpGet = new HttpGet(uri);
        if (headers != null && headers.size() >0) {
            for (Map.Entryentry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 执行请求
        response = httpClient.execute(httpGet);
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());
    } finally {
        try {
            httpGet.releaseConnection();
            response.close();
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
3. POST请求
public static String doPostJson(String url, String jsonParam, Mapheaders) {
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = wrapClient(url);
    try {
        httpPost = new HttpPost(url);
        //addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值
        httpPost.addHeader("Content-type","application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);
//            entity.setContentType("text/json");
//            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
        httpPost.setEntity(entity);
        //是否有header
        if (headers != null && headers.size() >0) {
            for (Map.Entryentry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 执行请求
        response = httpClient.execute(httpPost);
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }

    } catch (Exception e) {
        throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());
    } finally {
        try {
            httpPost.releaseConnection();
            response.close();
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
3. 获取httpclient的方法

这里会根据url自动匹配需要的是http的还是https的client

创新互联于2013年开始,先为固阳等服务建站,固阳等地企业,进行企业商务咨询服务。为固阳企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
private static CloseableHttpClient wrapClient(String url) {
      CloseableHttpClient client = HttpClientBuilder.create().build();
      if (url.startsWith("https")) {
          client = getCloseableHttpsClients();
      }
      return client;
  }
4. 对于https的需要自己实现一下client
private static CloseableHttpClient getCloseableHttpsClients() {
    // 采用绕过验证的方式处理https请求
    SSLContext sslcontext = createIgnoreVerifySSL();
    // 设置协议http和https对应的处理socket链接工厂的对象
    RegistrysocketFactoryRegistry = RegistryBuilder.create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);
    // 创建自定义的httpsclient对象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
    return client;
}
private static SSLContext createIgnoreVerifySSL() {
        // 创建套接字对象
        SSLContext sslContext = null;
        try {
            //指定TLS版本
            sslContext = SSLContext.getInstance("TLSv1.2");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("[创建套接字失败:] " + e.getMessage());
        }
        // 实现X509TrustManager接口,用于绕过验证
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        try {
            //初始化sslContext对象
            sslContext.init(null, new TrustManager[]{trustManager}, null);
        } catch (KeyManagementException e) {
            throw new RuntimeException("[初始化套接字失败:] " + e.getMessage());
        }
        return sslContext;
    }

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


新闻名称:Http、Https请求工具类-创新互联
新闻来源:http://bjjierui.cn/article/hjcoe.html

其他资讯