首页 > 编程语言 >java Http请求工具类

java Http请求工具类

时间:2022-11-30 10:13:11浏览次数:39  
标签:java String URL stringBuilder param connection new Http 请求

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpUtils {

    public static void main(String[] args) {
        String res = sendGetRequest("https://desk.zol.com.cn/");
        log.info(res);
    }


    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();

        //URL url = new URL(uri);
        // 这种方式可以解决在weblogic下部署的时候报错,在tomcat下也可以正常运行
        URL url = new URL(null,uri,new sun.net.www.protocol.https.Handler());
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        httpsConn.setRequestMethod(method);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        return httpsConn;
    }

    private static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    private static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] kb = new byte[1024];
        int len;
        while ((len = bais.read(kb)) != -1) {
            os.write(kb, 0, len);
        }
        os.flush();
        os.close();
        bais.close();
    }

    public static byte[] doGet(String uri) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
        return getBytesFromStream(httpsConn.getInputStream());
    }

    public static byte[] doPost(String uri, String data, String token) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
        httpsConn.setRequestProperty("Content-Type", "application/json");
        if (!"".equals(token) && token != null) {
            httpsConn.setRequestProperty("x-access-token", token); // 设置令牌
        }
        setBytesToStream(httpsConn.getOutputStream(), data.getBytes("gbk"));
        return getBytesFromStream(httpsConn.getInputStream());
    }


    /**
     * @Description http get请求
     * @param url 接口地址
     * @param charset 编码格式
     * @return java.util.String
     */
    public static String sendGet(String url, String charset) throws Exception {
        URL realurl = new URL(url);
        HttpURLConnection con = (HttpURLConnection) realurl.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)";
        con.setRequestProperty("User-Agent", USER_AGENT);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
        String inputLine;
        StringBuilder result = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            result.append(inputLine);
            result.append("\r\n");
        }
        in.close();
        con.disconnect();
        return result.toString();
    }

    /**
     * 发送get请求,没有参数
     *
     * @param url
     * @return
     */
    public static String sendGetRequest(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl
                    .openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应 (防止中文乱码可以换成“gbk”)
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGetRequest(String url, List<HashMap<String, String>> param) {
        String result = "";
        BufferedReader in = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(url);
            stringBuilder.append("?");
            for (HashMap<String, String> item : param) {
                Set<Map.Entry<String, String>> entrySet = item.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    stringBuilder.append(entry.getKey());
                    stringBuilder.append("=");
                    stringBuilder.append(entry.getValue());
                    stringBuilder.append("&");
                }
            }
            stringBuilder.substring(0,stringBuilder.length()-1);
            String totalUrl = stringBuilder.substring(0,stringBuilder.length()-1).toString();
            // System.out.println(totalUrl);
            URL realUrl = new URL(totalUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl
                    .openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 发送get请求,返回的有可能有非200的错误信息
     * @param url
     * @param param
     * @return
     */
    public static JSONObject sendGet(String url, List<HashMap<String, String>> param) {
        String result = "";
        BufferedReader in = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(url);
            stringBuilder.append("?");
            for (HashMap<String, String> item : param) {
                Set<Map.Entry<String, String>> entrySet = item.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    stringBuilder.append(entry.getKey());
                    stringBuilder.append("=");
                    stringBuilder.append(entry.getValue());
                    stringBuilder.append("&");
                }
            }
            stringBuilder.substring(0,stringBuilder.length()-1);
            String totalUrl = stringBuilder.substring(0,stringBuilder.length()-1).toString();
            // System.out.println(totalUrl);
            log.info(totalUrl);
            URL realUrl = new URL(totalUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl
                    .openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            // 如果是200状态码
            if(connection.getResponseCode() == 200){
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }else {
                // 获取错误信息
                in = new BufferedReader(new InputStreamReader(
                        connection.getErrorStream(), "utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 返回JSONobject
        return JSON.parseObject(result);
    }


    /**
     * @Description http post请求
     * @param url 接口地址
     * @param param 参数
     * @return java.util.String
     */
    public static String sendPost(String url, String param) throws Exception {
        PrintWriter out;
        BufferedReader in;
        StringBuilder result = new StringBuilder();
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        out.close();
        in.close();
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    public static String sendPost(String url, HashMap<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl
                    .openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (HashMap.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    // System.out.println(entry.getKey()+":"+entry.getValue());
                }
                System.out.println("param:" + param.toString());
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result.toString();
    }
}

标签:java,String,URL,stringBuilder,param,connection,new,Http,请求
From: https://www.cnblogs.com/Fantasyfzg/p/16937575.html

相关文章

  • 【java异常排查】 报错原因及排查【异常 解决方法】【经验总结】
    ​ 报错一:org.apache.jasper.JasperException:/xxx/xxx/xx.jsp(line:2312,column:334)TheJSPspecificationrequiresthatanattributenameisprecededbywh......
  • IntelliJ IDEA 2022.2.3注释快捷键(java)
    注释行和代码块使用Ctrl斜杠注释掉任意一行使用相同的快捷方式取消注释注释行:将文本光标置于该行中的任意位置,然后按Ctrl斜杠。选择几行,然后使用Ctrl斜杠注释掉要......
  • JavaScript合集(流程控制语句)
    流程控制条件判断语句条件分支语句循环语句条件判断语句if语句语法: if(条件表达式){ 语句 } ------- if(a>10){alert('a比10大')......
  • [XState] Create Actor in Vanilla Javascript
     functioncountBehavior(state,event){if(event.type==="INC"){return{...state,count:state.count+1}}}functioncreateA......
  • ajax请求报SON parse error
     1、如果用@RequestBody接受boot的参数1)前端采用的js对象传会报400JSON转化异常:Resolved[org.springframework.http.converter.HttpMessageNotReadableException:JS......
  • Java常用IO流
    字节输入输出流FileInputStream字节输入流常用方法:intread(byte[]b,intoff,intlen)返回读取的长度,读取失败返回-1。最多读取len个字节,读来的数据存放在b中,从第b......
  • Java中使用commons-io组件
    安装配置在其官网(CommonsIO–DownloadApacheCommonsIO)下载好之后,在项目中导入使用1、复制文件voidcopyFile(finalFilesrcFile,finalFiledestFile)//复......
  • pip Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not
      #解决方案 把…\anaconda3\Library\bin加入到系统环境变量即可。总是提示SSL有问题,然而只是SSL就在bin里边,所以没有生效。主要参考:https://github.com/conda/co......
  • 一个有趣的nginx HTTP 400响应问题分析
    背景之前在一次不规范HTTP请求引发的nginx响应400问题分析与解决中写过客户端query参数未urlencode导致的400问题,当时的结论是:对于query参数带空格的请求,由于其不符合HT......
  • 23条JavaScript初学者应知的最佳实践方法
    1、优先使用===,而不是==JavaScript使用两种相等性操作符:===|!==和==|!=。通常认为做比较的最佳实践是使用前一组操作符。“若两个操作数的类型和值相同,那么===比较的结果为......