欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot如何使用httpcomponents實現(xiàn)http請求

 更新時間:2023年07月17日 10:24:08   作者:青銅愛碼士  
這篇文章主要介紹了Spring Boot使用httpcomponents實現(xiàn)http請求的示例代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

基于org.apache.httpcomponents的httpclient實現(xiàn),其它的實現(xiàn)方式都行。

1. pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>registerTest</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>server</module>
        <module>provider1</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>
</project>

2. HttpClient實現(xiàn)get和post方法

package http.client;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClient {
    private String url;
    private String contentType;
    private String encoding;
    private JSONObject data;
    public HttpClient(String url, String encoding, String contentType, JSONObject data) {
        this.url = url;
        this.data = data;
        this.encoding = encoding == null ? "UTF-8" : encoding;
        this.contentType = contentType == null ? "application/json" : contentType;
    }
    public String httpGet() throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception("調(diào)用服務端異常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("從服務端返回結(jié)果: " + resultData);
        httpClient.close();
        return resultData;
    }
    public String httpPost() throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String json = JSONObject.toJSONString(data);
        StringEntity entity = new StringEntity(json);
        entity.setContentEncoding(encoding);
        entity.setContentType(contentType);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception("調(diào)用服務端異常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("從服務端返回結(jié)果: " + resultData);
        httpClient.close();
        return resultData;
    }
}

3. 創(chuàng)建springboot工程,提供接口訪問

package register.control;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import register.list.RegisterList;
@RestController
@RequestMapping("/register")
public class Register {
    @Autowired
    RegisterList registerList;
    @PostMapping("/register")
    public String register(@RequestBody JSONObject data) {
        //處理注冊邏輯
        return registerList.add(data.getString("name"), data.getString("ip"));
    }
    @GetMapping("/list/{name}")
    public Object getList(@PathVariable(value = "name", required = true) String name) {
        //獲取注冊列表
        return registerList.getByName(name);
    }
    @GetMapping("/list/all")
    public Object getList() {
        return registerList.getAll();
    }
}

4. 創(chuàng)建springboot工程,實現(xiàn)http請求

通過ApplicationRunner 實現(xiàn)啟動自動運行。

package common.register;
import com.alibaba.fastjson.JSONObject;
import http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class Register implements ApplicationRunner {
    @Value("${model.name}")
    String name;
    @Value("${model.host}")
    String host;
    @Value("${model.port}")
    String port;
    @Value("${register.url}")
    String url;
    //發(fā)送注冊消息
    @Override
    public void run(ApplicationArguments args) throws Exception {
        JSONObject data = new JSONObject() {{
            put("name", name);
            put("ip", "http://" + host + ":" + port);
        }};
        HttpClient client = new HttpClient(url, null, null, data);
        client.httpPost();
    }
}

結(jié)果:成功返回

在這里插入圖片描述

到此這篇關(guān)于Spring Boot使用httpcomponents實現(xiàn)http請求的文章就介紹到這了,更多相關(guān)Spring Boot使用httpcomponents內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot 如何解決cross跨域請求的問題

    springboot 如何解決cross跨域請求的問題

    這篇文章主要介紹了springboot 如何解決cross跨域請求的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java 線程池全面總結(jié)與詳解

    Java 線程池全面總結(jié)與詳解

    在一個應用程序中,我們需要多次使用線程,也就意味著,我們需要多次創(chuàng)建并銷毀線程。而創(chuàng)建并銷毀線程的過程勢必會消耗內(nèi)存。而在Java中,內(nèi)存資源是及其寶貴的,所以,我們就提出了線程池的概念
    2021-10-10
  • Spring Boot兩種配置文件properties和yml區(qū)別

    Spring Boot兩種配置文件properties和yml區(qū)別

    這篇文章主要為大家介紹了java面試中常見問到的Spring Boot兩種配置文件properties和yml區(qū)別解答,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • Spring?Boot開發(fā)RESTful接口與http協(xié)議狀態(tài)表述

    Spring?Boot開發(fā)RESTful接口與http協(xié)議狀態(tài)表述

    這篇文章主要為大家介紹了Spring?Boot開發(fā)RESTful接口與http協(xié)議狀態(tài)表述,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-03-03
  • synchronized底層實現(xiàn)原理

    synchronized底層實現(xiàn)原理

    這篇文章主要介紹了synchronized底層實現(xiàn)原理,想弄懂它的實現(xiàn)synchronized的原理,我們只能通過看編譯好的字節(jié)碼文件,下面文章的詳細內(nèi)容,我們就先從測試類開始吧,需要的小伙伴可以參考一下
    2022-01-01
  • SpringBoot讀取自定義配置文件方式(properties,yaml)

    SpringBoot讀取自定義配置文件方式(properties,yaml)

    這篇文章主要介紹了SpringBoot讀取自定義配置文件方式(properties,yaml),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Mybatis MapperScannerConfigurer自動掃描Mapper接口生成代理注入到Spring的方法

    Mybatis MapperScannerConfigurer自動掃描Mapper接口生成代理注入到Spring的方法

    這篇文章主要給大家介紹了關(guān)于Mybatis MapperScannerConfigurer自動掃描將Mapper接口生成代理注入到Spring的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2019-03-03
  • Spring Security之LogoutSuccessHandler注銷成功操作方式

    Spring Security之LogoutSuccessHandler注銷成功操作方式

    這篇文章主要介紹了Spring Security之LogoutSuccessHandler注銷成功操作方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 排序算法圖解之Java歸并排序的實現(xiàn)

    排序算法圖解之Java歸并排序的實現(xiàn)

    歸并排序是建立在歸并操作上的一種有效,穩(wěn)定的排序算法,該算法是采用分治法(Divide?and?Conquer)的一個非常典型的應用。本文主要介紹了歸并排序的實現(xiàn),需要的可以參考一下
    2022-11-11
  • 聊聊在Servlet中怎么上傳文件

    聊聊在Servlet中怎么上傳文件

    很多朋友不清楚在Servlet中怎么上傳文件,談到這個問題,首先需要我們掌握開發(fā)servlet的步驟,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2021-05-05

最新評論