基于springboot的HttpClient、OKhttp、RestTemplate对比

HttpClient详细

Httpclient基础!!!!实战训练!!!!-CSDN博客

OKhttp使用

OKhttp导包

复制代码
 <!-- ok的Http连接池 -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>

Get请求

java 复制代码
//okHttpClient
        //创建一个新的 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        //创建一个请求对象
        Request request = new Request.Builder()
                .url("http://localhost:8090/api/product/test")
                .get()
                .build();
        //发送请求并接收响应
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
        response.body().close();

post请求:

java 复制代码
//okHttpClient
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","123456");
       /* System.out.println("jsonObeject对象   :"+jsonObject);
        System.out.println("toJSONString()方法:"+jsonObject.toJSONString());
        System.out.println("toString()方法    :"+jsonObject.toString());
        System.out.println("String.valueOf方法:"+String.valueOf(jsonObject));*/
        //转化为字符串
        String s1=jsonObject.toJSONString();
        //构建请求体(RequestBody): 你可以根据需要发送不同类型的请求体。以下示例演示如何发送 JSON 格式的请求体:
        RequestBody requestBody = RequestBody.create(s1, MediaType.parse("application/json; charset=utf-8"));
        //创建一个请求对象
        Request request = new Request.Builder()
                .url("http://localhost:8080/admin/employee/login")
                .post(requestBody)//设置请求方法为 POST 并设置请求体
                .addHeader("Authorization", "Bearer your_token_here")  // 添加授权请求头(可选)
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());

        response.body().close();

toString()、String.valueOf()以及toJSONString()的区别及用法-CSDN博客

扩展知识:

  1. RequestBody.create()

RequestBody.create() 是 OkHttp 提供的一个静态方法,用于构造一个 RequestBody 对象。在发送 HTTP 请求时,RequestBody 通常包含了请求的内容(例如 POST 请求中的 JSON 数据、表单数据等)。

RequestBody.create() 有两个参数:

  • 第一个参数是请求体的内容,可以是一个 Stringbyte[]InputStream 等形式。
  • 第二个参数是请求体的媒体类型(MediaType),它描述了请求体的内容类型。

2、MediaType.parse("application/json; charset=utf-8")

MediaType 是 OkHttp 中用于描述内容类型的类。它包含了关于请求或响应数据格式的元数据。MediaType.parse() 方法用于解析一个字符串并返回一个 MediaType 对象。

在这里,"application/json; charset=utf-8" 表示请求体的内容类型是 JSON 格式,并且使用了 UTF-8 字符编码。

具体来说:

  • "application/json" 表示请求体的格式是 JSON。
  • charset=utf-8 指定了请求体数据采用 UTF-8 编码格式。

RestTemplate使用

1. 基本配置

在 Spring 中,RestTemplate 通常是作为一个 Bean 注册到 Spring 容器中的,可以在 Spring 配置类中进行配置。例如:

java 复制代码
package com.example.demo1.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class TestConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

通过这种方式,RestTemplate 可以在 Spring 容器中管理,并且可以注入到其他类中。

2. 发送 GET 请求

RestTemplate 提供了多种方法来发送 GET 请求,最常用的是 getForObject()getForEntity()

示例:发送 GET 请求
java 复制代码
@SpringBootTest
class Demo1ApplicationTests {

    @Autowired
    private RestTemplate restTemplate;
    @Test
    public void test() throws IOException {
        String url = "http://localhost:8090/api/product/test";
        String response = restTemplate.getForObject(url, String.class);
        System.out.println(response);

    }
相关推荐
Jeled4 小时前
Retrofit 与 OkHttp 全面解析与实战使用(含封装示例)
android·okhttp·android studio·retrofit
Jeled1 天前
Android 网络层最佳实践:Retrofit + OkHttp 封装与实战
android·okhttp·kotlin·android studio·retrofit
allk554 天前
OkHttp源码解析(一)
android·okhttp
allk554 天前
OkHttp源码解析(二)
android·okhttp
aFakeProgramer4 天前
拆分PDF.html 办公小工具
okhttp
一壶浊酒..5 天前
ajax局部更新
前端·ajax·okhttp
洛克大航海9 天前
Ajax基本使用
java·javascript·ajax·okhttp
whltaoin15 天前
Java 网络请求 Jar 包选型指南:从基础到实战
java·http·okhttp·网络请求·retrofit
华农第一蒟蒻16 天前
谈谈跨域问题
java·后端·nginx·安全·okhttp·c5全栈
一直向钱17 天前
android 基于okhttp的socket封装
android·okhttp