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

SpringBoot 接口開發(fā)教程(httpclient客戶端)

 更新時間:2022年03月09日 09:46:23   作者:紗布1213  
這篇文章主要介紹了SpringBoot 接口開發(fā)教程(httpclient客戶端),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

SpringBoot接口開發(fā)

服務(wù)端

@RestController
@RequestMapping("/landary")
public class landaryController {
 
    @RequestMapping("adduser")
    public JSONObject addUser(@RequestBody JSONObject userEntity)
    {
        System.out.println(JSONObject.toJSONString(userEntity));
        JSONObject json=new JSONObject();
        json.fluentPut("code","500").fluentPut("result",userEntity);
        return json;
    }
 
    @RequestMapping("showuser")
    public Object showUser()
    {
        return JSON.toJSONString("hhh");
    } 
}

客戶端post請求

 public static String sendSms(String uid,String title,String content){
        HttpClient httpclient = new DefaultHttpClient();
 
 
        String smsUrl="http://127.0.0.1:8088/landary/adduser";
        HttpPost httppost = new HttpPost(smsUrl);
        String strResult = "";
 
        try {
            JSONObject jobj = new JSONObject();
            jobj.put("uid", uid);
            jobj.put("title", title);
            jobj.put("content",content);
 
            System.out.println(jobj.toString());
         //   nameValuePairs.add(new BasicNameValuePair("msg", (jobj.toString())));
    /*        httppost.addHeader("Content-type", "application/json; charset=utf-8");
            httppost.setHeader("Accept", "application/json");
            httppost.setEntity(new StringEntity(jobj.toString(), Charset.forName("UTF-8")));*/
 
           StringEntity s = new StringEntity(jobj.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//發(fā)送json數(shù)據(jù)需要設(shè)置contentType
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
					/*讀返回?cái)?shù)據(jù)*/
                String conResult = EntityUtils.toString(response
                        .getEntity());
                System.out.println(conResult);
               JSONObject sobj = new JSONObject();
               sobj = JSONObject.parseObject(conResult);
                String result = sobj.getString("result");
                String code = sobj.getString("code");
                if(code.equals("500")){
                    System.out.println(result);
                    strResult += "發(fā)送成功";
                }else{
                    strResult += "發(fā)送失敗,"+code;
                }
 
            } else {
                String err = response.getStatusLine().getStatusCode()+"";
                strResult += "發(fā)送失敗:"+err;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return strResult;
    }

get請求

/**
     * 發(fā)送 get請求
     */
    public void get() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 創(chuàng)建httpget.
            HttpGet httpget = new HttpGet("http://127.0.0.1:8088/landary/showuser");
            System.out.println("executing request " + httpget.getURI());
            // 執(zhí)行g(shù)et請求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 獲取響應(yīng)實(shí)體
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印響應(yīng)狀態(tài)
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印響應(yīng)內(nèi)容長度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印響應(yīng)內(nèi)容
                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

SpringBoot之httpclient使用

超文本傳輸協(xié)議(HTTP,HyperText Transfer Protocol)是互聯(lián)網(wǎng)上應(yīng)用最為廣泛的一種網(wǎng)絡(luò)協(xié)議。所有的WWW文件都必須遵守這個標(biāo)準(zhǔn)。而HttpClient是可以支持http相關(guān)協(xié)議的工具包

它有如下功能:

1.實(shí)現(xiàn)了所有的http方法(GET,POST,PUT,HEAD 等)

2.支持自動轉(zhuǎn)向

3.支持 HTTPS 協(xié)議

4.支持代理服務(wù)器等

既然HttpClient使用這么廣泛,則本文講解下Spring Boot 中怎么使用HttpClient.如下:

引入相關(guān)依賴

? ? ? ?<!-- http所需包 -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId>
? ? ? ? ? ? <artifactId>httpclient</artifactId>
? ? ? ? </dependency>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId>
? ? ? ? ? ? <artifactId>httpcore</artifactId>
? ? ? ? </dependency>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId>
? ? ? ? ? ? <artifactId>httpmime</artifactId>
? ? ? ? </dependency>
? ? ? ? ?<!-- /http所需包 -->
? ? ? ? ?<!-- 數(shù)據(jù)解析所需包 --> ??
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.apache.commons</groupId>
? ? ? ? ? ? <artifactId>commons-lang3</artifactId>
? ? ? ? ? ? <version>3.4</version>
? ? ? ? </dependency>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>commons-lang</groupId>
? ? ? ? ? ? <artifactId>commons-lang</artifactId>
? ? ? ? ? ? <version>2.6</version>
? ? ? ? </dependency> ??
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>com.alibaba</groupId>
? ? ? ? ? ? <artifactId>fastjson</artifactId>
? ? ? ? ? ? <version>1.2.4</version>
? ? ? ? </dependency>
? ? ? ? <!-- /數(shù)據(jù)解析所需包 --> ??

編寫相關(guān)工具類

寫個http的工具類,以便業(yè)務(wù)代碼直接調(diào)用,如下:

/**
?* Http工具類
?*/
public class HttpUtils {
? ? /**
? ? ?* 發(fā)送POST請求
? ? ?* @param url 請求url
? ? ?* @param data 請求數(shù)據(jù)
? ? ?* @return 結(jié)果
? ? ?*/
? ? @SuppressWarnings("deprecation")
? ? public static String doPost(String url, String data) {
? ? ? ? CloseableHttpClient httpClient = HttpClients.createDefault();
? ? ? ? HttpPost httpPost = new HttpPost(url);
? ? ? ? RequestConfig requestConfig = RequestConfig.custom()
? ? ? ? ? ? ? ? .setSocketTimeout(10000).setConnectTimeout(20000)
? ? ? ? ? ? ? ? .setConnectionRequestTimeout(10000).build();
? ? ? ? httpPost.setConfig(requestConfig);
? ? ? ? String context = StringUtils.EMPTY;
? ? ? ? if (!StringUtils.isEmpty(data)) {
? ? ? ? ? ? StringEntity body = new StringEntity(data, "utf-8");
? ? ? ? ? ? httpPost.setEntity(body);
? ? ? ? }
? ? ? ? // 設(shè)置回調(diào)接口接收的消息頭
? ? ? ? httpPost.addHeader("Content-Type", "application/json");
? ? ? ? CloseableHttpResponse response = null;
? ? ? ? try {
? ? ? ? ? ? response = httpClient.execute(httpPost);
? ? ? ? ? ? HttpEntity entity = response.getEntity();
? ? ? ? ? ? context = EntityUtils.toString(entity, HTTP.UTF_8);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.getStackTrace();
? ? ? ? } finally {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? response.close();
? ? ? ? ? ? ? ? httpPost.abort();
? ? ? ? ? ? ? ? httpClient.close();
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? e.getStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return context;
? ? }
? ? /**
? ? ?* 解析出url參數(shù)中的鍵值對
? ? ?* @param url url參數(shù)
? ? ?* @return 鍵值對
? ? ?*/
? ? public static Map<String, String> getRequestParam(String url) {
? ? ? ? Map<String, String> map = new HashMap<String, String>();
? ? ? ? String[] arrSplit = null;
? ? ? ? // 每個鍵值為一組
? ? ? ? arrSplit = url.split("[&]");
? ? ? ? for (String strSplit : arrSplit) {
? ? ? ? ? ? String[] arrSplitEqual = null;
? ? ? ? ? ? arrSplitEqual = strSplit.split("[=]");
? ? ? ? ? ? // 解析出鍵值
? ? ? ? ? ? if (arrSplitEqual.length > 1) {
? ? ? ? ? ? ? ? // 正確解析
? ? ? ? ? ? ? ? map.put(arrSplitEqual[0], arrSplitEqual[1]);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? if (arrSplitEqual[0] != "") {
? ? ? ? ? ? ? ? ? ? map.put(arrSplitEqual[0], "");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return map;
? ? }
}

業(yè)務(wù)代碼中使用

業(yè)務(wù)中代碼使用,拼裝請求Url和請求數(shù)據(jù),就可以調(diào)用工具類里的doPost()方法開始直接使用咯。如下:

private String getFileStorePath(String courtId, String seesionId){
? ? ? ? String fileStorePath = StringUtils.EMPTY;
? ? ? ? //請求參數(shù)
? ? ? ? String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";
? ? ? ? String fileServiceUrl="http://111.11.11.11:8086";
? ? ? ? //發(fā)送請求,獲取結(jié)果
? ? ? ? String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data); ? ?
? ? ? ? if(StringUtils.isNotBlank(result)){
? ? ? ? ? ? com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result);
? ? ? ? ? ? fileStorePath = jsonobject.getString("path");
? ? ? ? ? ? logger.info("fileStorePath = " + fileStorePath);
? ? ? ? }
? ? ? ? return fileStorePath;
? ? }

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java 壓縮圖片并打包成ZIP文件的示例

    Java 壓縮圖片并打包成ZIP文件的示例

    這篇文章主要介紹了Java 壓縮圖片并打包成ZIP文件的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-12-12
  • Java基于狀態(tài)模式實(shí)現(xiàn)的文檔編輯模式切換功能實(shí)例

    Java基于狀態(tài)模式實(shí)現(xiàn)的文檔編輯模式切換功能實(shí)例

    這篇文章主要介紹了Java基于狀態(tài)模式實(shí)現(xiàn)的文檔編輯模式切換功能,結(jié)合實(shí)例形式詳細(xì)分析了狀態(tài)模式的概念、原理及java使用狀態(tài)模式實(shí)現(xiàn)文檔編輯模式切換操作相關(guān)技巧與注意事項(xiàng),需要的朋友可以參考下
    2018-05-05
  • Spring Boot 通過AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法

    Spring Boot 通過AOP和自定義注解實(shí)現(xiàn)權(quán)限控制的方法

    這篇文章主要介紹了Spring Boot 通過AOP和自定義注解實(shí)現(xiàn)權(quán)限控制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • ResponseBodyAdvice踩坑及解決

    ResponseBodyAdvice踩坑及解決

    這篇文章主要介紹了ResponseBodyAdvice踩坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • J2EE中的struts2表單細(xì)節(jié)處理

    J2EE中的struts2表單細(xì)節(jié)處理

    這篇文章主要介紹了J2EE中的struts2表單細(xì)節(jié)處理的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • 在springboot中使用p6spy方式

    在springboot中使用p6spy方式

    這篇文章主要介紹了在springboot中使用p6spy方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 詳解java IO流之緩沖流的使用

    詳解java IO流之緩沖流的使用

    本文主要介紹了java的IO流中的緩沖流的使用,緩沖流分為字節(jié)和字符緩沖流。分享了有關(guān)它們的實(shí)例代碼,具有一定的參考價值,下面跟著小編一起來看下吧
    2017-01-01
  • Java多線程下解決資源競爭的7種方法詳解

    Java多線程下解決資源競爭的7種方法詳解

    這篇文章主要介紹了Java多線程下解決資源競爭的7種方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Java代碼是如何被CPU狂飆起來的

    Java代碼是如何被CPU狂飆起來的

    無論是剛剛?cè)腴TJava的新手還是已經(jīng)工作了的老司機(jī),恐怕都不容易把Java代碼如何一步步被CPU執(zhí)行起來這個問題完全講清楚。本文就帶你詳細(xì)了解Java代碼到底是怎么運(yùn)行起來的。感興趣的同學(xué)可以參考閱讀
    2023-03-03
  • 帶你快速搞定java多線程(5)

    帶你快速搞定java多線程(5)

    這篇文章主要介紹了java多線程編程實(shí)例,分享了幾則多線程的實(shí)例代碼,具有一定參考價值,加深多線程編程的理解還是很有幫助的,需要的朋友可以參考下
    2021-07-07

最新評論

肇州县| 丰县| 化德县| 定襄县| 定日县| 繁昌县| 茌平县| 自贡市| 永登县| 贵定县| 曲水县| 苏尼特左旗| 富顺县| 马龙县| 达尔| 盘山县| 静乐县| 兴安盟| 肥乡县| 基隆市| 社会| 阿坝县| 浮梁县| 涞水县| 嵩明县| 淮安市| 巧家县| 平原县| 塔城市| 通山县| 杭锦旗| 廉江市| 青浦区| 个旧市| 宝应县| 富宁县| 荥阳市| 阿瓦提县| 吉安市| 永川市| 车致|