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();
            }
        }
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐