API工具类

一、创建ApiUtil工具类

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

public class ApiUtil {

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static void trustAllHosts() {
        //Create a trust manager that does not validate certificate chains
        //创建不验证证书链的信任管理器
        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) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // Install the all-trusting trust manager
        //安装所有信任信任管理器
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //GET请求
    public static String sendGet(String path) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        OutputStreamWriter out = null;
        try {
            trustAllHosts();//不信任管理器
            URL url = new URL(path);
            //通过请求地址判断请求类型(http或者是https)
            if (url.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.setRequestMethod("GET");//设置连接方式:GET
            conn.setConnectTimeout(15000);//设置连接主机服务器的超时时间:15000毫秒
            conn.setReadTimeout(60000);//设置读取远程返回的数据时间:60000毫秒
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);//设置为true可使用conn.getOutputStream().write()
            conn.setDoInput(true);//设置为true可使用conn.getInputStream().read();
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//获取URLConnection对象对应的输出流
            out.flush();//缓冲数据
            InputStream is = conn.getInputStream();//获取URLConnection对象对应的输入流
            //构造一个字符流缓存
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (out != null) {
                    in.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("GET请求完成,关闭输出输入流!");
        }
        return result;
    }

    //POST请求
    public static String sendPost(String path) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        OutputStreamWriter out = null;
        try {
            trustAllHosts();//不信任管理器
            URL url = new URL(path);
            //通过请求地址判断请求类型(http或者是https)
            if (url.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestMethod("POST");//设置连接方式:POST
            conn.setConnectTimeout(15000);//设置连接主机服务器的超时时间:15000毫秒
            conn.setReadTimeout(60000);//设置读取远程返回的数据时间:60000毫秒
            conn.setUseCaches(false);//Post请求不能使用缓存
            conn.setDoOutput(true);//设置为true才可以使用conn.getOutputStream().write()
            conn.setDoInput(true);//才可以使用conn.getInputStream().read();
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//获取URLConnection对象对应的输出流
            out.flush();//缓冲数据
            InputStream is = conn.getInputStream();//获取URLConnection对象对应的输入流
            //构造一个字符流缓存
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    in.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("POST请求完成,关闭输出输入流!");
        }
        return result;
    }
}

二、调用ApiUtil

 @RequestMapping("/")
 public String Test() throws IOException {
        String url = "https://api.apiopen.top/getAllUrl";
        String type = "GET";
        return ApiUtil.getRequestResult(url,type);
    }
发布了40 篇原创文章 · 获赞 173 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_41920732/article/details/90056038
今日推荐