java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot使用httpcomponents

Spring Boot如何使用httpcomponents实现http请求

作者:青铜爱码士

这篇文章主要介绍了Spring Boot使用httpcomponents实现http请求的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

基于org.apache.httpcomponents的httpclient实现,其它的实现方式都行。

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实现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("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("从服务端返回结果: " + 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("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("从服务端返回结果: " + resultData);
        httpClient.close();
        return resultData;
    }
}

3. 创建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. 创建springboot工程,实现http请求

通过ApplicationRunner 实现启动自动运行。

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;
    //发送注册消息
    @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();
    }
}

结果:成功返回

在这里插入图片描述

到此这篇关于Spring Boot使用httpcomponents实现http请求的文章就介绍到这了,更多相关Spring Boot使用httpcomponents内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文