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();
        }
    }
}
相关推荐
菜鸟小九17 分钟前
JUC(入门1-3章)
java·juc
LJianK131 分钟前
Java中的类、普通类,抽象类,接口的区别
java·开发语言
LiLiYuan.1 小时前
【Java线程 vs 虚拟机线程】
java·开发语言
2402_881319301 小时前
跨服务通信兜底机制-Java 回传失败无持久重试队列,报告可能静默丢失。
java·开发语言·python
用户8307196840821 小时前
Spring也会“选择困难”?五种方案帮你搞定@Autowired多bean注入
spring boot
明灯伴古佛1 小时前
面试:对Spring AOP的理解
java·spring·面试
Nyarlathotep01131 小时前
ConcurrentHashMap源码分析
java·后端
Barkamin2 小时前
多线程简单介绍
java·开发语言·jvm
小比特_蓝光2 小时前
算法篇二----二分查找
java·数据结构·算法
NE_STOP3 小时前
SpringCloud进阶--RabbitMQ消息队列(完结)
spring