spring-boot调用外部接口的两种方式(feign与httpClient)

1.feign方式只适合于调用注册了Eureka注册中心的接口

例子:

pom.xml

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
    </properties>
        <!--   spring-cloud-starter-feign 用于连接外部接口-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

主类加上@EnableFeignClients:

@EnableFeignClients
@MapperScan(basePackages = {"com.example.dao.mapper"})
@SpringBootApplication
public class ResetApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ResetApiApplication.class, args);
    }
}

feign文件

文件路径:com.example.service.feign.ShoppingCartFeignClient

@FeignClient(url = "http://localhost:666", value = "11")
public interface TestFeignClient {
    @PostMapping("/Test/getNum")
    ResultBody<?> getNum(@RequestBody TestReqVO reqVO);
}

注意:url:  调用的服务,和我们的服务,不在同一个注册中心,那么此时就需要使用一个url来指定被调用的服务的地址,name: 在同一个注册中心,直接用name,url和name都存在,则默认使用url。name(与value一样)

controller文件



    @ApiOperation(value = "用feign调接口", response = TestNumRespVO.class)
    @PostMapping("/getnumByFeign")
    public ResultBody getStudentListByFeign(@RequestBody TestReqVO reqVO) {
        return feignClient.getNum(reqVO);
    }

2.用HttpClient可任意调用外部接口

(1)使用POST方式访问HTTP

package com.example.httpclient.httpClientDemo;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;


public class HttpPostDemo {

    public static void main(String[] args) throws JSONException {
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpPost对象
        HttpPost post = new HttpPost("https:12345/v1");
        // 3. 设置POST请求传递参数 post.setEntity
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("a", "aaa");
        jsonObject.put("token", "222");
        HashMap<String, Object> data = new HashMap<>();
        data.put("ccc", "ccc");
        data.put("version", "1.0");
        ArrayList<String> ids = new ArrayList<>();
        ids.add("6666");
        data.put("ids", ids);
        jsonObject.put("data", data);

        post.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8));  // 这里这只字符格式,可以防止中文乱码

        // 4. 执行请求并处理响应
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("响应内容:");
                System.out.println(EntityUtils.toString(entity));
            }
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

(2)使用Get方式访问HTTP

package com.example.httpclient.httpClientDemo;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpGetDemo {
    public static void main(String[] args) {
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpGet对象
        HttpGet httpGet = new HttpGet("https://www.baidu.com/cache/fpid/chromelib_1_1.js?_=1636686387459");
        CloseableHttpResponse response = null;
        try {
            // 3. 执行GET请求
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine());
            // 4. 获取响应实体
            HttpEntity entity = response.getEntity();
            // 5. 处理响应实体
            if (entity != null) {
                System.out.println("长度:" + entity.getContentLength());
                System.out.println("内容:" + EntityUtils.toString(entity));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三尾鱼网络科技

如果对您有帮助,赠人玫瑰手留余

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值