最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java使用httpclient 發(fā)送請(qǐng)求的示例

 更新時(shí)間:2023年10月19日 11:54:23   作者:有夢(mèng)想的菜  
HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議,這篇文章主要介紹了java使用httpclient 發(fā)送請(qǐng)求的示例,需要的朋友可以參考下

HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。

一、使用的Jar包

首先需要在maven中引入如下包

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.13</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.18</version>
</dependency>

二、接口代碼

Get的無參/有參請(qǐng)求

/**
 * @param url     接口地址
 * @param headers 請(qǐng)求頭
 * @Description get請(qǐng)求
 */
public static String getData(String url, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpGet.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8).trim();
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
        StringResult = "errorException:" + e.getMessage();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

請(qǐng)求實(shí)列:在這里無參請(qǐng)求就不展示,可自行試驗(yàn)

Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
String data = getData("https://api.vvhan.com/api/covid?city=重慶", headers);
System.out.println(data);

請(qǐng)求結(jié)果:

{
  "success": true,
  "data": {
    "updatetime": "2022-12-23 09:46:10",
    "country": "中國",
    "province": "重慶",
    "city": "重慶",
    "now": {
      "sure_new_loc": "未公布",
      "sure_new_hid": "未公布",
      "sure_present": 3108
    },
    "history": {
      "sure_cnt": 10452,
      "cure_cnt": 7337,
      "die_cnt": 7
    },
    "danger": {
      "high_risk": 0,
      "medium_risk": 0
    }
  }
}

Post請(qǐng)求(application/x-www-form-urlencoded)

/**
 * @param url     接口地址
 * @param list    NameValuePair(簡(jiǎn)單名稱值對(duì)節(jié)點(diǎn)類型)類似html中的input
 * @param headers 請(qǐng)求頭(默認(rèn)Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
 * @Description post請(qǐng)求
 */
public static String postData(String url, ArrayList<NameValuePair> list, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    if (list != null && !list.isEmpty()) {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
        httpPost.setEntity(formEntity);
    }
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpPost.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        StringResult = "errorException:" + e.getMessage();
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

請(qǐng)求實(shí)列:

ArrayList<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "用戶名"));
list.add(new BasicNameValuePair("password", "1234"));
String s = postData("http://127.0.0.1:3000/aaa/file/testPost.jsp", list, null);
System.out.println(s);

請(qǐng)求結(jié)果:

用戶名
1234
application/x-www-form-urlencoded; charset=UTF-8

Post請(qǐng)求(application/json)

/**
 * @param url        接口地址
 * @param jsonString json字符串
 * @param headers    請(qǐng)求頭(默認(rèn)Content-Type:application/json; charset=UTF-8)
 * @Description post Json 請(qǐng)求
 */
public static String postJsonData(String url, @NotNull String jsonString, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    StringEntity jsonEntity = new StringEntity(jsonString, Consts.UTF_8);
    jsonEntity.setContentEncoding(Consts.UTF_8.name());
    httpPost.setEntity(jsonEntity);
    httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpPost.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        StringResult = "errorException:" + e.getMessage();
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

請(qǐng)求實(shí)列:

JSONObject jsonObject = new JSONObject();
jsonObject.put("demo", "456789");
jsonObject.put("demo1", "哈哈哈愛發(fā)火");
String s = postJsonData("http://127.0.0.1:3000/api/workflow/v1/insert2", jsonObject.toJSONString(), null);
System.out.println(s);

請(qǐng)求結(jié)果:

Get請(qǐng)求url拼接

/**
 * @param url    接口地址(無參數(shù)/有參)
 * @param params 拼接參數(shù)集合
 * @Description get請(qǐng)求URL拼接參數(shù) & URL編碼
 */
public static String getAppendUrl(String url, Map<String, String> params) {
    StringBuffer buffer = new StringBuffer(url);
    if (params != null && !params.isEmpty()) {
        for (String key : params.keySet()) {
            if (buffer.indexOf("?") >= 0) {
                buffer.append("&");
            } else {
                buffer.append("?");
            }
            String value = "";
            try {
                value = URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            buffer.append(key)
                    .append("=")
                    .append(value);
        }
    }
    return buffer.toString();
}

請(qǐng)求實(shí)列:

Map<String, String> params = new HashMap<>();
params.put("city", "重慶");
params.put("number", "手機(jī)號(hào)");
String appendUrl = getAppendUrl("https://TestGetSplice/index", params);
String appendUrl1 = getAppendUrl("https://TestGetSplice/index?a=33", params);
System.out.println(appendUrl);
System.out.println(appendUrl1);

請(qǐng)求結(jié)果:

https://TestGetSplice/index?number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86
https://TestGetSplice/index?a=33&number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86

三、使用的類

import com.alibaba.fastjson.JSONObject;
import com.sun.istack.internal.NotNull;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

四、標(biāo)準(zhǔn)字符集的常量定義

這些字符集保證在Java平臺(tái)的每個(gè)實(shí)現(xiàn)上都可用。

import java.nio.charset.StandardCharsets;
StandardCharsets.UTF_8

五、請(qǐng)求狀態(tài)常量

import org.apache.http.HttpStatus;
// 200
HttpStatus.SC_OK

到此這篇關(guān)于java使用httpclient 發(fā)送請(qǐng)求的文章就介紹到這了,更多相關(guān)httpclient 發(fā)送請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java自定義類數(shù)組報(bào)null的相關(guān)問題及解決

    Java自定義類數(shù)組報(bào)null的相關(guān)問題及解決

    這篇文章主要介紹了Java自定義類數(shù)組報(bào)null的相關(guān)問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 聊聊springboot靜態(tài)資源加載的規(guī)則

    聊聊springboot靜態(tài)資源加載的規(guī)則

    這篇文章主要介紹了springboot靜態(tài)資源加載的規(guī)則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • springboot的java配置方式(實(shí)例講解)

    springboot的java配置方式(實(shí)例講解)

    下面小編就為大家分享一篇實(shí)例講解springboot的java配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2017-11-11
  • 盤點(diǎn)總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率

    盤點(diǎn)總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率

    這篇文章主要為大家介紹了盤點(diǎn)總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • JVM內(nèi)置函數(shù)Intrinsics介紹

    JVM內(nèi)置函數(shù)Intrinsics介紹

    這篇文章主要介紹了JVM內(nèi)置函數(shù)Intrinsics,我們將學(xué)習(xí)什么是intrinsics(內(nèi)部/內(nèi)置函數(shù)),以及它們?nèi)绾卧贘ava和其他基于JVM的語言中工作,需要的朋友可以參考一下
    2022-02-02
  • 分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作過程(推薦)

    分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作過程(推薦)

    這篇文章主要介紹了分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作,包括定時(shí)任務(wù)的使用場(chǎng)景和常見的定時(shí)任務(wù),通過本文學(xué)習(xí)幫助大家該選擇哪個(gè)分布式任務(wù)調(diào)度平臺(tái),對(duì)此文感興趣的朋友一起看看吧
    2022-04-04
  • 教你幾個(gè)?Java?編程中使用技巧

    教你幾個(gè)?Java?編程中使用技巧

    枯燥的編程中總得有些樂趣,今天我們不談?wù)撃切└呱畹募寄?,教你幾個(gè)在編程中的奇技淫巧,說不定在某些時(shí)候還能炫耀一番呢,今天小編教你幾個(gè)?Java?編程中使用技巧,感興趣的朋友參考下吧
    2022-12-12
  • Java實(shí)現(xiàn)DBF文件讀寫操作的完整指南

    Java實(shí)現(xiàn)DBF文件讀寫操作的完整指南

    DBF是一種數(shù)據(jù)庫文件格式,主要存儲(chǔ)結(jié)構(gòu)化數(shù)據(jù),本文將詳細(xì)介紹如何在Java中使用JDBF庫來讀取和創(chuàng)建DBF文件,有需要的小伙伴可以參考一下
    2025-04-04
  • jpa?onetomany?使用級(jí)連表刪除被維護(hù)表數(shù)據(jù)時(shí)的坑

    jpa?onetomany?使用級(jí)連表刪除被維護(hù)表數(shù)據(jù)時(shí)的坑

    這篇文章主要介紹了jpa?onetomany?使用級(jí)連表刪除被維護(hù)表數(shù)據(jù)時(shí)的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Springmvc的運(yùn)行流程圖文詳解

    Springmvc的運(yùn)行流程圖文詳解

    今天小編就為大家分享一篇關(guān)于Springmvc的運(yùn)行流程圖文詳解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-01-01

最新評(píng)論

如皋市| 尉犁县| 迁安市| 许昌县| 沁阳市| 神池县| 墨江| 濮阳县| 文成县| 石家庄市| 抚宁县| 乐陵市| 滨海县| 左贡县| 临泽县| 格尔木市| 灵石县| 巫山县| 鸡泽县| 灌南县| 安远县| 汶川县| 历史| 开化县| 万宁市| 麻栗坡县| 长海县| 临江市| 巴彦淖尔市| 陈巴尔虎旗| 三原县| 塘沽区| 陇南市| 高阳县| 邯郸县| 盈江县| 祁连县| 青河县| 昭觉县| 博兴县| 乌拉特中旗|