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();
        }
    }
}
相关推荐
重生之我是Java开发战士11 分钟前
【Java EE】快速上手Spring Boot
java·spring boot·java-ee
從南走到北11 分钟前
JAVA国际版一对一视频交友视频聊天系统源码支持H5 + APP
java·微信·微信小程序·小程序·音视频·交友
go__Ahead26 分钟前
【Java-JMM】Happens-before原则
java
pcm1235671 小时前
java中的单例模式
java·开发语言·单例模式
xxxxxxllllllshi1 小时前
【Elasticsearch查询DSL API完全指南:从入门到精通】
java·大数据·elasticsearch·搜索引擎·面试·全文检索·jenkins
自在极意功。1 小时前
动态规划核心原理与高级实战:从入门到精通(Java全解)
java·算法·动态规划·最优子结构·重叠子问题
杨DaB1 小时前
【SpringCloud】回顾微服务
spring·spring cloud·微服务
oioihoii1 小时前
当无符号与有符号整数相遇:C++中的隐式类型转换陷阱
java·开发语言·c++
鼠鼠我捏,要死了捏2 小时前
深入剖析Java垃圾回收性能优化实战指南
java·性能优化·gc
Pota-to成长日记2 小时前
代码解析:基于时间轴(Timeline)的博客分页查询功能
java