java springboot 集成 okHttp 发送get、post请求

在 Java Spring Boot 项目中可以很方便地集成OkHttp来发送GETPOST请求。以下是具体步骤:

一、添加依赖

在项目的pom.xml文件中添加OkHttp的依赖:

xml 复制代码
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.11.0</version>
</dependency>

二、发送 GET 请求

  1. 创建一个工具类来封装OkHttp的请求方法:
java 复制代码
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpUtil {

    public static String sendGetRequest(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
               .url(url)
               .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }
}
  1. 在需要发送GET请求的地方调用这个方法:
java 复制代码
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            String response = OkHttpUtil.sendGetRequest("https://api.example.com/data");
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、发送 POST 请求

  1. 在工具类中添加发送POST请求的方法:
java 复制代码
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpUtil {
    //... 前面的 sendGetRequest 方法

    public static String sendPostRequest(String url, String jsonData) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonData, mediaType);
        Request request = new Request.Builder()
               .url(url)
               .post(body)
               .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }
}
  1. 在需要发送POST请求的地方调用这个方法:
java 复制代码
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            String jsonData = "{\"key\":\"value\"}";
            String response = OkHttpUtil.sendPostRequest("https://api.example.com/post-endpoint", jsonData);
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,sendGetRequest方法用于发送GET请求,sendPostRequest方法用于发送POST请求并传入要发送的 JSON 数据。请确保在实际使用中处理可能出现的异常情况,并根据实际需求调整请求的 URL 和数据。

相关推荐
天河归来16 分钟前
springboot框架redis开启管道批量写入数据
java·spring boot·redis
合作小小程序员小小店21 分钟前
web网页,在线%食谱推荐系统%分析系统demo,基于vscode,uniapp,vue,java,jdk,springboot,mysql数据库
vue.js·spring boot·vscode·spring·uni-app
张先shen24 分钟前
Elasticsearch RESTful API入门:全文搜索实战
java·大数据·elasticsearch·搜索引擎·全文检索·restful
codervibe25 分钟前
如何用 Spring Security 构建无状态权限控制系统(含角色菜单控制)
java·后端
codervibe29 分钟前
项目中如何用策略模式实现多角色登录解耦?(附实战代码)
java·后端
TCChzp31 分钟前
synchronized全链路解析:从字节码到JVM内核的锁实现与升级策略
java·jvm
大葱白菜32 分钟前
🧩 Java 枚举详解:从基础到实战,掌握类型安全与优雅设计
java·程序员
笑衬人心。34 分钟前
在 Mac 上安装 Java 和 IntelliJ IDEA(完整笔记)
java·macos·intellij-idea
SimonKing41 分钟前
颠覆传统IO:零拷贝技术如何重塑Java高性能编程?
java·后端·程序员
sniper_fandc1 小时前
SpringBoot系列—MyBatis(xml使用)
java·spring boot·mybatis