/**********************https 接口'*******************/

/**
 * 安全证书管理器
 */
public class MyX509TrustManager implements X509TrustManager {

@Override
    public void checkClientTrusted(final X509Certificate[] chain,
            final String authType) throws CertificateException {
    }

@Override
    public void checkServerTrusted(final X509Certificate[] chain,
            final String authType) throws CertificateException {
    }

@Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

/**
     * 主要说明了如何访问带有未经验证证书的HTTPS站点
     *
     * @param requestUrl 例如:获取微信用户信息接口 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(final String requestUrl,
            final String requestMethod, final String outputStr) {
        JSONObject jsonObject = null;
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        HttpsURLConnection httpUrlConn = null;
        InputStreamReader inputStreamReader = null;
        final StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            final TrustManager[] tm = { new MyX509TrustManager() };
            final SSLContext sslContext = SSLContext.getInstance("SSL",
                    "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            final SSLSocketFactory ssf = sslContext.getSocketFactory();

final URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

// 当有数据需要提交时
            if (null != outputStr) {
                final OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

// 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);

String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

jsonObject = JSONObject.fromObject(buffer.toString());
      }catch (final Exception e) {
            log.error("https request error:", e);
        } finally {
            // 释放资源
           .......
        }
        return jsonObject;
    }

/**********************http 接口'*******************/

@Slf4j
public class HttpSendUtil {
    private static final String APPLICATION_JSON = "application/json";
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
    private static RequestConfig requestConfig = null;
    final static ObjectMapper objectMapper = new ObjectMapper();
    static {
        requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(50000).setConnectTimeout(50000)
                .setSocketTimeout(50000).build();
    }

/**
     * 默认编码utf -8
     * 解决返回数据中文乱码问题
     * @param entity
     *            must not be null
     */
    public static String getContentCharSet(final HttpEntity entity)
            throws ParseException {
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }
        String charset = null;
        if (entity.getContentType() != null) {
            final HeaderElement values[] = entity.getContentType()
                    .getElements();
            if (values.length > 0) {
                final NameValuePair param = values[0]
                        .getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }

if (StringUtils.isEmpty(charset)) {
            charset = "UTF-8";
        }
        return charset;
    }

/**
     * Get 请求
     *
     * @param url
     * @return
     */
    public static String httpGet(final String url) {
        final CloseableHttpClient httpClient = getCloseableHttpClient();
        final HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        CloseableHttpResponse response = null;
        String result = null;
        String charset = HTTP.UTF_8;
        try {
            response = httpClient.execute(httpGet);
            final HttpEntity entity = response.getEntity();
            if (null != entity) {
                System.out.println("响应状态码:" + response.getStatusLine());
                System.out
                        .println("-------------------------------------------------");
                // System.out.println("响应内容:" + EntityUtils.toString(entity));
                System.out
                        .println("-------------------------------------------------");
                charset = getContentCharSet(entity);
                result = EntityUtils.toString(entity, charset);
                EntityUtils.consume(entity);
            }
        } catch (final Exception e) {
            e.printStackTrace();
        } finally {
            closeHttpResponseAndHttpClient(response, httpClient);
        }
        return result;
    }

/**
     * Post 请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String httpPostWithJSON(final String url, final String json) {
        final CloseableHttpClient httpClient = getCloseableHttpClient();
        final HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        CloseableHttpResponse response = null;
        String result = null;
        String charset = HTTP.UTF_8;
        try {
            // 将JSON进行UTF-8编码,以便传输中文
            final String encoderJson = URLEncoder.encode(json, charset);
            final StringEntity se = new StringEntity(encoderJson);
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    APPLICATION_JSON));
            httpPost.setEntity(se);

response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                final HttpEntity entity = response.getEntity();
                charset = getContentCharSet(entity);
                result = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            } else {
                log.warn("请求失败!");
            }
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            closeHttpResponseAndHttpClient(response, httpClient);
        }
        return result;
    }

private static void closeHttpResponseAndHttpClient(
            final CloseableHttpResponse httpResponse,
            final CloseableHttpClient client) {
        try {
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != client) {
                client.close();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

private static CloseableHttpClient getCloseableHttpClient() {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig)
                .build();
    }
}

java实现https,https接口请求的更多相关文章

  1. Java 调用Restful API接口的几种方式--HTTPS

    摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful ...

  2. java实现 HTTP/HTTPS请求绕过证书检测代码实现

    java实现 HTTP/HTTPS请求绕过证书检测代码实现 1.开发需求 需要实现在服务端发起HTTP/HTTPS请求,访问其他程序资源. 2.URLConnection和HTTPClient的比较 ...

  3. Java调用Http/Https接口(6)--RestTemplate调用Http/Https接口

    RestTemplate是Spring提供的用于访问Http接口的客户端,提供同步的API:在将来的Spring版本中可能会过时,将逐渐被WebClient替代.文中所使用到的软件版本:Java 1. ...

  4. Java调用Http/Https接口(5)--HttpAsyncClient调用Http/Https接口

    HttpAsyncClient是HttpClient的异步版本,提供异步调用的api.文中所使用到的软件版本:Java 1.8.0_191.HttpClient 4.1.4. 1.服务端 参见Java ...

  5. Java调用Http/Https接口(4)--HttpClient调用Http/Https接口

    HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...

  6. Java调用Http/Https接口(3)--Commons-HttpClient调用Http/Https接口

    Commons-HttpClient原来是Apache Commons项目下的一个组件,现已被HttpComponents项目下的HttpClient组件所取代:作为调用Http接口的一种选择,本文介 ...

  7. Java实现 HTTP/HTTPS请求绕过证书检测

    java实现 HTTP/HTTPS请求绕过证书检测 一.Java实现免证书访问Https请求 创建证书管理器类 import java.security.cert.CertificateExcepti ...

  8. PHP:CURL分别以GET、POST方式请求HTTPS协议接口api

    1.curl以GET方式请求https协议接口 //注意:这里的$url已经包含参数了,不带参数你自己处理哦GET很简单 function curl_get_https($url){ $curl = ...

  9. PHP函数CURL分别以GET、POST方式请求HTTPS协议接口api

    1.curl以GET方式请求https协议接口 function curl_get_https($url){ $curl = curl_init(); // 启动一个CURL会话 curl_setop ...

  10. PHP:CURL分别以GET、POST方式请求HTTPS协议接口api【转】

    1.curl以GET方式请求https协议接口 //注意:这里的$url已经包含参数了,不带参数你自己处理哦GET很简单 function curl_get_https($url){ $curl = ...

随机推荐

  1. InitializingBean和init-method

    [spring的InitializingBean的 afterPropertiesSet 方法 和 init-method配置的 区别联系] InitializingBean Spring的Initi ...

  2. Ehcache(06)——监听器

    http://haohaoxuexi.iteye.com/blog/2119353 监听器 Ehcache中监听器有两种,监听CacheManager的CacheManagerEventListene ...

  3. ISO13485给企业带来的益处

    1.ISO13485变强制性认证,日益受到欧美和中国政府机构的重视,有利于消除国际贸易中的技术壁垒,是进入国际市场的通行证: 2.提高和改善企业的管理水平,增加企业的知名度: 3.提高和保证产品的质量 ...

  4. JavaScript的角色巨变和Web技术的发展

    曾经JavaScript是职业程序员看不上眼的脚本语言,如今只有高级程序员才能驾驭它. JavaScript性质和地位的天翻地覆,正是Web技术飞速变化的印证. 最初职业程序员轻视JavaScript ...

  5. Response.Redirect 打开新窗体的两种方法

    普通情况下,Response.Redirect 方法是在server端进行转向,因此,除非使用 Response.Write("<script>window.location=' ...

  6. 【M30】代理类

    1.考虑二维数组,在栈上分配,必须在编译时确定大小,也就是大小是常量.另外一点,C++不支持在堆上分配二维数组.怎么解决这个问题? 二维数组可以看成,一维数组的数组.因此,可以使用代理类,Array2 ...

  7. Swift学习笔记十一

    类与结构体 Swift中,并不要求把自定义类或结构的接口和实现写在不同的文件中.你在一个文件中定义类或结构体,那么这个类或结构体的外部接口就自动可以在其他代码中使用了. 类和结构有很多相似和区别,相同 ...

  8. C# DateTime 日期加1天 减一天 加一月 减一月 等方法

    //今天 DateTime.Now.Date.ToShortDateString(); //昨天,就是今天的日期减一 DateTime.Now.AddDays(-).ToShortDateString ...

  9. Codeforces Round #307 (Div. 2) C. GukiZ hates Boxes 贪心/二分

    C. GukiZ hates Boxes Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/551/ ...

  10. Chrome 开发者工具的Timeline和Profiles提高Web应用程序的性能

    Chrome 开发者工具的Timeline和Profiles提高Web应用程序的性能 二.减少 HTTP 的请求数    当用户浏览页面时,如果我们在用户第一次访问时将一些信息一次性加载到客户端缓存, ...