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();
        }
    }
}
相关推荐
历程里程碑5 分钟前
1 . Git本地操作:版本控制 跨平台协作 仓库核心
java·开发语言·数据结构·c++·git·gitee·github
hekung11 分钟前
maven的lifecycle与idea的run
java·maven
阿维的博客日记17 分钟前
为什么 ConcurrentHashMap 采用 synchronized 加锁而不采用ReentrantLock
java·juc
阿丰资源26 分钟前
java项目(附资料)-基于SpringBoot+MyBatisPlus+MySQL+Layui的药品管理系统
java·spring boot·mysql
云恒要逆袭27 分钟前
Java SE、EE、ME到底啥区别?我被这个问题困扰了一整年
java·java ee
鱼鳞_34 分钟前
Java学习笔记_Day27(Stream流)
java·笔记·学习
身如柳絮随风扬34 分钟前
Servlet:访问流程、核心接口与生命周期
java·servlet·web
indexsunny34 分钟前
互联网大厂Java面试实战:从Spring Boot到微服务架构的深度探讨
java·数据库·spring boot·安全·微服务·监控·面试实战
夕除35 分钟前
javaweb--03
java
m0_677904841 小时前
K8s学习
java·学习·kubernetes