spring boot请求http接口的三种方式

spring boot请求http接口的三种方式

HttpURLConnection

HttpURLConnection 是 Java 中的 HTTP 客户端实现,,适用于简单的请求需要。

public class HttpURLConnectionUtil {
    /**
     *
     * @param url 请求url
     * @param params 请求参数
     * @return
     * @throws IOException
     */
    public static String post(String url, String params) throws IOException {
        // 打开连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        // 设置请求参数
        conn.setRequestMethod("POST");
        // 设置允许添加参数
        conn.setDoOutput(true);
        // 打开输出流
        OutputStream os = conn.getOutputStream();
        os.write(params.getBytes());
        os.flush();
        os.close();
        // 判断请求结果
        if (conn.getResponseCode() == 200) {
            // 读取响应内容
            InputStream is = conn.getInputStream();
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            // 关闭连接
            br.close();
            is.close();
            return sb.toString();
        }

        return null;
    }
}

HttpURLConnection主要工作内容:打开socket连接,封装http请求报文,解析请求报文。

okhttp

OkHttp 是一个第三方的 HTTP 客户端库,它比 Java 标准的 HttpURLConnection 更高效、更实用。主要特点包括:

  1. 比 HttpURLConnection 快得多,HttpURLConnection 每个请求都会创建一个新的套接字,而 OkHttp 使用连接池,重用其他请求的套接字。
  2. 支持同步和异步请求。异步调用不会阻塞线程。
  3. 支持 GZIP 压缩,减少网络流量。
    引入依赖:
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.9</version>
</dependency>

代码

public class OkHttpUtil {
    // get请求
    public static String get(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url(url)
            .build();
        
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    // post请求
    public static String post(String url, String params) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), params);
        Request request = new Request.Builder()
            .url(url) 
            .post(body)
            .build();
            
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}

OpenFeign

OpenFeign是SpringCloud自己研发的,在Feign的基础上支持了Spring MVC的注解,如@RequesMapping等等。是SpringCloud中的第二代负载均衡客户端。底层是封装HttpClient技术。
引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

spring boot开启OpenFeign,在启动类加上@EnableFeignClients注解

@SpringBootApplication
@EnableFeignClients
public class ApplicationStarter {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationStarter.class, args);
    }
}

定义FeignClient

@FeignClient(value = "user",  url = "http://localhost:8080/")
public interface UserFeign {

    @PostMapping("/user/queryList")
    String query(@RequestBody User param);
}

OpenFeign默认客户端HttpURLConnection执行,使用okttp提高性能
引入依赖

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-okhttp</artifactId>
</dependency>

开启

feign:
  okhttp:
    enabled: false
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值