http https工具

为了应付在web项目中调用其他http或https接口的需求,本文根据 此文章 部分内容改写为以下两个发起http以及https请求的工具类


引用工具前须导入依赖

      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.5</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpmime</artifactId>
          <version>4.5.5</version>
      </dependency>

Http工具:

    public class HttpUtils {
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();
    private static String  charset="utf-8";
    private static  String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
    private static int socketTimeout=2000;
    private static int connectTimeout=2000;


    /**参数直接附在url上
     * @param url
     * @return String
     */
    public static String sendGet(String url) {
        return excuteHttpGet(url);
    }

    /**
     * map参数形式
     * @param url
     * @param params
     * @return String
     */
    public static String sendGet(String url,Map<String,String> params){
        url+="?";
        for (String key:params.keySet()) {
            url+=key+"="+params.get(key)+"&";
        }
        return excuteHttpGet(url);
    }

    /**
     * 发送HttpPost请求
     * @param url
     * @param map 参数
     * @return String
     */
    public static String sendPost(String url, Map<String, String> map) {
        // 设置参数
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        // 取得HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 参数放入Entity
        httpPost.setEntity(formEntity);
        return excuteHttpPost(httpPost);
    }

    /**发送HttpPost请求
     * @param url
     * @param file 参数为文件
     * @return String
     */
    public static String sendPost(String url, File file) {
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("media", new FileBody(file));
        httpPost.setEntity(multipartEntity.build());
        return excuteHttpPost(httpPost);
    }
    /**
     * 发送HttpPost请求
     * @param url
     * @param jsonStr 参数为json字符串
     * @return String
     */
    public static String sendPost(String url, String jsonStr) {
        // 字符串编码
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        // 设置content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 接收参数设置
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        return excuteHttpPost(httpPost);
    }
    /**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return String
     */
    public static String sendPost(String url) {
        // 得到一个HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        return excuteHttpPost(httpPost);
    }

    /**
     * httpPost公用方法
     * @param httpPost
     * @return
     */
    private static  String excuteHttpPost(HttpPost httpPost){
        CloseableHttpResponse response = null;
        String result = null;
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            // 执行post请求
            response = httpclient.execute(httpPost);
            // 得到entity
            HttpEntity entity = response.getEntity();
            // 得到字符串
            if (entity != null) {
                result = EntityUtils.toString(entity,charset);
            }
        } catch (IOException e) {
            System.out.println("IO异常:"+e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("关闭Response对象出现异常:"+e.getMessage());
                }
            }
        }
        return result;
    }
    private static String excuteHttpGet(String url){
        String result=null;
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("User-Agent", userAgent);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity,charset);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("关闭Response对象出现异常:"+e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * 默认utf-8
     * @param charset
     */
    public static void setCharset(String charset) {
        HttpUtils.charset = charset;
    }
    public static void setUserAgent(String userAgent) {
        HttpUtils.userAgent = userAgent;
    }

    /**
     * 默认2秒
     * @param socketTimeout
     */
    public static void setSocketTimeout(int socketTimeout) {
        HttpUtils.socketTimeout = socketTimeout;
    }

    /**
     * 默认2秒
     * @param connectTimeout
     */
    public static void setConnectTimeout(int connectTimeout) {
        HttpUtils.connectTimeout = connectTimeout;
    }
}   

Https工具类:

    public class HttpsUtils {
    private static final CloseableHttpClient httpsclient = createSSLClientDefault();
    private static String  charset="utf-8";
    private static  String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
    private static int socketTimeout=2000;//超时时间
    private static int connectTimeout=2000; //超时时间

    public static CloseableHttpClient createSSLClientDefault(){
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
                //信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }



    /**参数直接附在url上
     * @param url
     * @return String
     */
    public static String sendGet(String url) {
        return excuteHttpGet(url);
    }

    /**
     * map参数形式
     * @param url
     * @param params
     * @return String
     */
    public static String sendGet(String url,Map<String,String> params){
        url+="?";
        for (String key:params.keySet()) {
            url+=key+"="+params.get(key)+"&";
        }
        return excuteHttpGet(url);
    }

    /**
     * 发送HttpPost请求
     * @param url
     * @param map 参数
     * @return String
     */
    public static String sendPost(String url, Map<String, String> map) {
        // 设置参数
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        // 取得HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 参数放入Entity
        httpPost.setEntity(formEntity);
        return excuteHttpPost(httpPost);
    }

    /**发送HttpPost请求
     * @param url
     * @param file 参数为文件
     * @return String
     */
    public static String sendPost(String url, File file) {
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("media", new FileBody(file));
        httpPost.setEntity(multipartEntity.build());
        return excuteHttpPost(httpPost);
    }
    /**
     * 发送HttpPost请求
     * @param url
     * @param jsonStr 参数为json字符串
     * @return String
     */
    public static String sendPost(String url, String jsonStr) {
        // 字符串编码
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        // 设置content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 接收参数设置
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        return excuteHttpPost(httpPost);
    }
    /**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return String
     */
    public static String sendPost(String url) {
        // 得到一个HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        return excuteHttpPost(httpPost);
    }

    /**
     * httpPost公用方法
     * @param httpPost
     * @return
     */
    private static  String excuteHttpPost(HttpPost httpPost){
        CloseableHttpResponse response = null;
        String result = null;
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            // 执行post请求
            response = httpsclient.execute(httpPost);
            // 得到entity
            HttpEntity entity = response.getEntity();
            // 得到字符串
            if (entity != null) {
                result = EntityUtils.toString(entity,charset);
            }
        } catch (IOException e) {
            System.out.println("IO异常:"+e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("关闭Response对象出现异常:"+e.getMessage());
                }
            }
        }
        return result;
    }
    private static String excuteHttpGet(String url){
        String result=null;
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("User-Agent", userAgent);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            response = httpsclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity,charset);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("关闭Response对象出现异常:"+e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * 默认utf-8
     * @param charset
     */
    public static void setCharset(String charset) {
        HttpsUtils.charset = charset;
    }
    public static void setUserAgent(String userAgent) {
        HttpsUtils.userAgent = userAgent;
    }

    /**
     * 默认2秒
     * @param socketTimeout
     */
    public static void setSocketTimeout(int socketTimeout) {
        HttpsUtils.socketTimeout = socketTimeout;
    }

    /**
     * 默认2秒
     * @param connectTimeout
     */
    public static void setConnectTimeout(int connectTimeout) {
        HttpsUtils.connectTimeout = connectTimeout;
    }
}

<center> Coding Blog     Github Blog </center>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,718评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,683评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,207评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,755评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,862评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,050评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,136评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,882评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,330评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,651评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,789评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,477评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,135评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,864评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,099评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,598评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,697评论 2 351