HTTPS 请求

5 篇文章 0 订阅
1 篇文章 0 订阅

1、HTTP共用方法 

 public String doHttp(String urlStr, String output){
        StringBuilder sb = new StringBuilder();
        HttpsURLConnection connection = null;//http链接
        try {
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("TLS");
            System.setProperty("https.protocols", "TLSv1");
            TrustManager[] tm={new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url = new URL(urlStr);//url创建
            connection = (HttpsURLConnection) url.openConnection();//打开链接
            connection.setRequestMethod("POST");//设置请求方法。还可以设置其他参数
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(30000);
            connection.setUseCaches(false);
            connection.setSSLSocketFactory(ssf);
            connection.setRequestProperty("Content-Type", "application/json");
            if (output != null) {
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), Charset.forName("UTF-8"));
                out.write(output);
                out.flush();
                out.close();
            }
            connection.connect();//正式链接请求

            InputStream in = connection.getInputStream();//正确返回结果,获得输入流

            //读取内容
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);//按行读取
            String temp = null;
            while ((temp = br.readLine()) != null) {//读取内容
                sb.append(temp);
            }
            br.close();
            isr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("未能正常连接到消息方服务!", e);
        } finally {
            //关闭链接
            if (connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();
    }

2、调用

//json 入参
//url 字符串地址
//str   为返回值
String str = doHttp(url, json.toString());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值