HttpUtil工具类及测试类

工具类

import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpClient {

    public static String sendHttp(String url, String param, Map<String, String> headers, String method, Integer timeOut) throws Exception {
        method = method == null ? "GET" : method;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        if (!StringUtils.isEmpty(param) && "GET".equalsIgnoreCase(method)) {
            url = url + "?" + param;
        }
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        if (timeOut != null && timeOut > 0) {
            conn.setReadTimeout(timeOut * 1000);
        }
        HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
        httpURLConnection.setRequestMethod(method.toUpperCase());
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpURLConnection.setRequestProperty(header.getKey(), header.getValue());
        }
        conn.setDoInput(true);
        if (!StringUtils.isEmpty(param) && "POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());

            out.print(param);
            out.flush();
        }

        httpURLConnection.connect();
        in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }

    public static String[] sendHttps(String url, String param, Map<String, String> headers, String method, Integer timeOut) throws Exception {
        method = method == null ? "GET" : method;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        if (!StringUtils.isEmpty(param) && "GET".equalsIgnoreCase(method)) {
            url = url + "?" + param;
        }

        HttpsURLConnection.setDefaultHostnameVerifier(new HttpClient().new NullHostNameVerifier());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        if (timeOut != null && timeOut > 0) {
            conn.setReadTimeout(timeOut * 1000);
        }
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) conn;
        httpsURLConnection.setRequestMethod(method.toUpperCase());
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpsURLConnection.setRequestProperty(header.getKey(), header.getValue());
        }
        conn.setDoInput(true);
        if (!StringUtils.isEmpty(param) && "POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());

            out.print(param);
            out.flush();
        }

        httpsURLConnection.connect();
        try {
            in = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            result = null;
        }
        return new String[]{String.valueOf(httpsURLConnection.getResponseCode()), result};
    }

    public class NullHostNameVerifier implements HostnameVerifier {
        /*
         * (non-Javadoc)
         *
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return true;
        }
    }

    static TrustManager[] trustAllCerts = new TrustManager[]{new 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;
        }
    }};

}

post测试类

import java.util.*;

public class Tests2 {

    public static void main(String[] args) {

        String host = "192.168.10.160:8080";
        String token = "xxxx";
        String longs = "https://" + host + "/api/applications";

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);
        headers.put("Accept", "application/json");
//       headers.put("Grpc-Metadata-Authorization","Bearer"+" "+token);
        headers.put("Content-Type", "application/json");
        //  headers.put("Accept", "text/xml");
//        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Connection", "keep-alive");
        headers.put("User-Agent", "Apache-HttpClient/4.5.2 (Java/1.8.0_144)");
        //  headers.put("Host", host);
        String[] result = new String[0];
        String ddd = "{\n" +
                "\t\"description\": \"测试应用4\",\n" +
                "\t\"name\": \"ceshiapp43\",\n" +
                "\t\"organizationID\": \"3\",\n" +
                "\t\"serviceProfileID\": \"a4a916e9-934e-49b4-9ff6-03ef4198ce02\"\n" +
                "}";
        try {
            result = HttpClient.sendHttps(longs, ddd, headers, "post", null);
            if (result[0].equals("200")) {
                System.out.println("0k");
            } else {
                System.out.println("nook");
            }
         
        } catch (Exception e) {
            System.out.println("异常");
            e.printStackTrace();

        }
/        int a=6;
//        List<Integer> numbers = getIntegers(a);
//
//        System.out.println(numbers);
    }


    private static List<Integer> getIntegers(int a) {
        Random random = new Random();
        List<Integer> numbers = new ArrayList<Integer>();
        int sum = 0;

        while (true) {
            int n = random.nextInt(100);
            sum += n;
            numbers.add(n);
            if (numbers.size() > a || sum > 100) {
                numbers.clear();
                sum = 0;
            }
            if (numbers.size() == a && sum == 100) {
                break;
            }
        }
        return numbers;
    }

}

猜你喜欢

转载自blog.csdn.net/reee112/article/details/84636894