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();
        }
    }
}
相关推荐
弯_弯几秒前
FDE 的工程能力画像:数据接入、PoC 与可复用资产的落地口径
java·服务器·开发语言
云和数据.ChenGuang1 小时前
print(f“a+b=“,result) print(f“a+b={result}“)区别
java·前端·人工智能·python·深度学习
2601_962885721 小时前
如何用 Python 算最大回撤和回撤恢复期?
java·数据库·python
毕业设计7032 小时前
(免费领源码)SSM董家湾线上点餐系统04682- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
java·redis·mysql·tomcat·maven·mybatis·ssm
Q26433650232 小时前
【有源码】基于SpringBoot+Vue的居民健康体检与慢病干预管理系统-面向智慧医疗的体检预约与健康知识服务平台
java·vue.js·spring boot·mysql·毕业设计·javaweb·课程设计
撸串-研究生3 小时前
基于Spring Boot的智慧社区垃圾分类与回收系统的设计与实现【附源码】
spring boot·后端·分类·垃圾分类·社区管理
悠仁さん3 小时前
非类型模板参数的特化与偏特化
java·数据结构·算法
鬼手点金3 小时前
上下文:Agent 的眼睛
java·前端·人工智能·git·深度学习
ly76893 小时前
PostgreSQL 流复制与高可用切换:主从延迟、同步提交与 Spring Boot 读写分离的边界
数据库·spring boot·postgresql·读写分离·流复制·高可用切换