Spring Boot使用httpcomponents实现http请求

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

1. pom文件


<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>registerTestartifactId>
    <packaging>pompackaging>
    <version>1.0-SNAPSHOTversion>
    <modules>
        <module>servermodule>
        <module>provider1module>
    modules>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.1.RELEASEversion>
        <relativePath/> 
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.23version>
        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请求_第1张图片

你可能感兴趣的:(spring,boot,http,后端)