springboot 调用外部接口方法

引入pom文件

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

请求方法get

java 复制代码
@RestController
public class WeatherController {

    @GetMapping("/weather")
    public String getWeather(@RequestParam("city") String city) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://*****")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                return "Failed to get weather data";
            }
        } catch (IOException e) {
            return "Error: " + e.getMessage();
        }
    }
}

post请求

java 复制代码
import okhttp3.*;

import java.io.IOException;

public class Example {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // 构造请求体
        RequestBody requestBody = new FormBody.Builder()
                .add("username", "admin")
                .add("password", "password")
                .build();

        // 构造请求对象
        Request request = new Request.Builder()
                .url("http://example.com/api/login")
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 处理响应数据
                System.out.println(response.body().string());
            } else {
                System.out.println("请求失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
utf8mb4安全女神39 分钟前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
带刺的坐椅1 小时前
Solon Server 启动模式深度解析:从 0.3MB 内核到 10+ Server 插件
java·http·solon·jetty·undertow
郝学胜-神的一滴1 小时前
干货版《算法导论》07:递归视角下的选择排序与归并排序
java·数据结构·c++·python·程序人生·算法·排序算法
掉鱼的猫1 小时前
Solon Server 启动模式深度解析:从 0.3MB 内核到 10+ Server 插件
java·http
shehuiyuelaiyuehao1 小时前
多线程入门
java·python·算法
星夜夏空991 小时前
FreeRTOS学习(7)——任务列表
java·前端·学习
han_hanker1 小时前
BeanUtils.copyProperties 和序列化的问题
java·开发语言·spring boot
野生技术架构师1 小时前
牛客网2026互联网大厂Java面试题汇总,附官方级答案解析
java·开发语言
西凉的悲伤2 小时前
Spring Boot 中 @Async(value = “alertThreadPool“) 是什么?为什么企业项目喜欢自定义线程池?
spring boot·多线程·async·异步
AZaLEan__2 小时前
多源 BFS
java·开发语言·算法