通用工具类

package com.meeting.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

/**
 * 
 * @ClassName: CommonUtil
 * @Description: 通用工具类
 * @author chengrui
 * @date 2017-3-28 上午9:33:01
 */
public class CommonUtil {

    /**
     * 
     * @Title: httpsRequest
     * @Description: 发送请求,返回JSONObject对象
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static JSONObject httpsRequest(String requestUrl,
        String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    try {
        // 使用自定义的信任管理器
        TrustManager[] tm = { new MyX509TrustManagerUtil() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        // 建立连接
        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(ssf);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 设置请求方式
        conn.setRequestMethod(requestMethod);
        // 当outputStr不为null时,向输出流写数据
        if (null != outputStr) {
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(outputStr.getBytes("UTF-8"));
        outputStream.close();
        }
        // 获取输入流
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(
            inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(
            inputStreamReader);
        // 读取响应内容
        StringBuffer buffer = new StringBuffer();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
        }
        // 关闭资源
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        conn.disconnect();
        jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (Exception e) {
        System.out.println("ERROR");
    }
    return jsonObject;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值