HttpUtil工具类及测试类

本文介绍了一个Java实现的HTTP与HTTPS客户端请求处理类,支持GET、POST与PUT方法,详细展示了如何设置请求头、参数及超时时间,并通过一个测试类演示了如何使用该类获取JWT令牌。

支持put


package cn.com.polycis.common.utils;

import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
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;

/**
 * <p> Date             :2018/1/18 </p>
 * <p> Module           : </p>
 * <p> Description      : </p>
 * <p> Remark           : </p>
 *
 * @author yangdejun
 * @version 1.0
 *          <p>--------------------------------------------------------------</p>
 *          <p>修改历史</p>
 *          <p>    序号    日期    修改人    修改原因    </p>
 *          <p>    1                                     </p>
 */
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();
        }

        if (!StringUtils.isEmpty(param) && "PUT".equalsIgnoreCase(method)) {
            ((HttpsURLConnection) conn).setRequestMethod("PUT");
            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;
        }
    }};


}

测试类:

package cn.com.polycis;

import cn.com.polycis.common.utils.HttpClient;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONException;


import java.util.*;

public class test5_getToken {

    public static void main(String[] args) throws JSONException {

        String host="192.168.10.108:8080";
 //       String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJsb3JhLWFwcC1zZXJ2ZXIiLCJleHAiOjE1NDM1NjY4MTIsImlzcyI6ImxvcmEtYXBwLXNlcnZlciIsIm5iZiI6MTU0MzQ4MDQxMiwic3ViIjoidXNlciIsInVzZXJuYW1lIjoiYWRtaW4ifQ.tSB9bAPOXzjYYJa3uDO_ZCduRE48ZiSpVeot8bwAJjo";
//        String longs = "https://" + host + "/api/devices/3333343167346b12/frames";

        String longs = "https://" + host + "/api/internal/login";

        Map<String, String> headers = new HashMap<>();
//        headers.put("Authorization", "Bearer" + token);
       headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json");
  //      headers.put("Authorization", "Bearer " + token);
        //  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];
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","admin");
        String param = jsonObject.toString();


        try {
             result = HttpClient.sendHttps(longs, param, headers, "post", null);
            //String get = HttpUtil.sendHttp(longs, null, HttpUtil.createHearder("Content-type = application/json"), "get", null);
           // System.out.println(get);
            JSONObject jsonObject1 = JSONObject.parseObject(result[1]);

            String tokens    = jsonObject1.getString("jwt");
            System.out.println(tokens);



            for(int i=0;i<result.length;i++){
                System.out.println(result[i]);
            }
            if (result[0].equals("200")) {
                System.out.println("0k");
            } else {
                System.out.println("nook");
            }

        } catch (Exception e) {
            System.out.println("异常");
            e.printStackTrace();

        }
        /*if (!result[0].equals("200")) {
            String das = result[1];
            System.out.println("是200"+das);
        }else{
            String das = result[1];
            System.out.println("不是200"+das);
        }*/

    }

    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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值