zoukankan      html  css  js  c++  java
  • Java 发送http请求

    参考自:https://blog.csdn.net/u012527802/article/details/70172357

    import javax.net.ssl.*;
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    /**
     * Created by deng on 2020/3/24.
     * 发送HTTP请求
     */
    public class HttpClient {
    
        public static void main(String[] args) {
            String url = "https://www.baidu.com";
            String s = HttpClient.sendHttpRequest(url, RequestMethod.GET);
            System.out.println(s);
        }
    
        /**
         * @param urlParam  url
         * @param requestMethod 请求方式
         * @return  返回String类型的字符串 ,如果请求失败,返回null
         */
        public static String sendHttpRequest(String urlParam,RequestMethod requestMethod){
            HttpURLConnection con = null;
            BufferedReader buffer = null;
            StringBuffer resultBuffer = null;
            InputStream ins = null;
            try {
                URL url = new URL(urlParam);
                //得到连接对象
                con = (HttpURLConnection) url.openConnection();
    
                //设置请求类型
                switch (requestMethod){
                    case GET:
                        con.setRequestMethod("GET");
                        break;
                    case POST:
                        con.setRequestMethod("POST");
                        break;
                }
                //据说post请求必须设置这两条,暂时不知道
                con.setDoOutput(true);  //允许写出
                con.setDoInput(true);   //允许读入
    
                con.setUseCaches(false);    //不使用缓存
    
                //得到响应码
                int responseCode = con.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //请求成功,得到响应流
                    ins = con.getInputStream();
                    //转化为字符串
                    resultBuffer = new StringBuffer();
                    String line;
                    //注意响应体的编码格式,可能会有乱码
                    buffer = new BufferedReader(new InputStreamReader(ins,"GBK"));
    
                    while((line=buffer.readLine())!=null){
                        resultBuffer.append(line);
                    }
                    //将resultBuffer返回即可
                    return resultBuffer.toString();
                }
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(ins!=null){
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return null;
        }
    
        /**
         * 发送https请求,忽略ssl证书错误
         * @param urlParam
         * @param requestMethod
         * @return
         */
        public static String sendHttpsRequestNoSSL(String urlParam,RequestMethod requestMethod){
            HttpURLConnection con = null;
            BufferedReader buffer = null;
            StringBuffer resultBuffer = null;
            InputStream ins = null;
            try {
                URL url = new URL(urlParam);
                //得到连接对象
                con = (HttpURLConnection) url.openConnection();
    
                SSLSocketFactory oldSocketFactory = null;
                HostnameVerifier oldHostnameVerifier = null;
    
                boolean useHttps = urlParam.startsWith("https");
                if (useHttps) {
                    HttpsURLConnection https = (HttpsURLConnection) con;
                    oldSocketFactory = trustAllHosts(https);
                    oldHostnameVerifier = https.getHostnameVerifier();
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }
    
                //设置请求类型
                switch (requestMethod){
                    case GET:
                        con.setRequestMethod("GET");
                        break;
                    case POST:
                        con.setRequestMethod("POST");
                        break;
                }
                //据说post请求必须设置这两条,暂时不知道
                con.setDoOutput(true);  //允许写出
                con.setDoInput(true);   //允许读入
    
                con.setUseCaches(false);    //不使用缓存
                con.connect();//连接
    
                //得到响应码
                int responseCode = con.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //请求成功,得到响应流
                    ins = con.getInputStream();
                    //转化为字符串
                    resultBuffer = new StringBuffer();
                    String line;
                    //注意响应体的编码格式,可能会有乱码
                    buffer = new BufferedReader(new InputStreamReader(ins,"GBK"));
    
                    while((line=buffer.readLine())!=null){
                        resultBuffer.append(line);
                    }
                    //将resultBuffer返回即可
                    return resultBuffer.toString();
                }
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(ins!=null){
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            return null;
        }
        /**
         * 覆盖java默认的证书验证
         */
        private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
    
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        }};
        /**
         * 设置不验证主机
         */
        private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        /**
         * 信任所有
         * @param connection
         * @return
         */
        private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
            SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                SSLSocketFactory newFactory = sc.getSocketFactory();
                connection.setSSLSocketFactory(newFactory);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return oldFactory;
        }
    }
    
    enum RequestMethod{
        GET,    //get请求
        POST    //post请求
    }
    View Code
  • 相关阅读:
    重构该何时登场
    重构
    中国剩余定理
    连分数的应用
    连分数的性质
    有限连分数与欧几里德除法的联系
    连分数
    费马大定理
    P4178 Tree 点分治
    LOJ 6029. 「雅礼集训 2017 Day1」市场
  • 原文地址:https://www.cnblogs.com/dch0/p/12582475.html
Copyright © 2011-2022 走看看