首页 技术 正文
技术 2022年11月20日
0 收藏 968 点赞 2,854 浏览 6819 个字

/**********************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();
    }
}

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905