码迷,mamicode.com
首页 > 编程语言 > 详细

java用HttpURLConnection发起HTTP/HTTPS请求

时间:2021-06-19 19:29:27      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:tor   iter   方式   style   Stub   secure   context   close   exce   

MyX509TrustManager.java
package com.demo.until;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

public class MyX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

    // 处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
    public static String httpRequest(String requestUrl, String requestMethod,
            String outputStr) {

        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);// 请求地址
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 创建连接对象
            conn.setDoOutput(true);// 是否输出
            conn.setDoInput(true);// 是否输入
            conn.setRequestMethod(requestMethod);// post Or get
            conn.setRequestProperty("Charset", "utf-8");
            conn.setFollowRedirects(false);
            conn.setInstanceFollowRedirects(false);
            conn.connect();// 发起连接
            // 往服务器端写内容 也就是发起http请求需要带的参数
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            // 读取服务器端返回的内容
            // PrintWriter out = new PrintWriter(new
            // OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            // out.println(obj);

            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /*
     * 处理https GET/POST请求 请求地址、请求方法、参数
     */
    public static String httpsRequest(String requestUrl, String requestMethod,
            String outputStr) {
        StringBuffer buffer = null;
        try {
            // 创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = { new MyX509TrustManager() };
            // 初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            ;
            // 获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            // 设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "gbk");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        //测试
        String testUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=xxxxxx";//淘宝获取手机号信息接口
        String url = "地址";
        String s = httpsRequest(url, "POST", null);
        System.out.println(s);
    }
}

 这里测试的是小程序获取openid

// 用code发起请求并获取oepnId
        MyX509TrustManager mx = new MyX509TrustManager();
        String s = mx
                .httpsRequest(
                        "https://api.weixin.qq.com/sns/jscode2session?appid=‘‘&secret=‘‘&js_code=‘‘
                            &grant_type=authorization_code",
                        "POST", null);
        //转JSON
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(s, map.getClass());
        String openId = (String) map.get("openid"); 

转载自:https://blog.csdn.net/qq_42129925/article/details/93891214

java用HttpURLConnection发起HTTP/HTTPS请求

标签:tor   iter   方式   style   Stub   secure   context   close   exce   

原文地址:https://www.cnblogs.com/guohu/p/14903210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!