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();
        }
    }
}
相关推荐
Jesse_EC36 分钟前
为什么我设置的 contentLength 到了消费端变成了 0?
java
vipxieliang36 分钟前
ValidX 的 Date 和 DateTime vs JPA 的 Temporal 对比
java·后端
杜touch38 分钟前
Spring框架的AnnotationConfigApplicationContext类启动的流程
java
AI人工智能+电脑小能手1 小时前
大白话说Java设计模式-26-策略模式(业务实战篇)
java·spring·设计模式·策略模式·支付系统·算法切换
不是光头 强2 小时前
Java 后端 AI 技术选型与学习路线
java·人工智能·学习
paopaokaka_luck2 小时前
基于springboot3+vue3的文山民族文化资源展示与推广平台(协同过滤算法、Echarts 图形化分析)
java·前端·spring boot·学习·echarts
eralong2 小时前
Java IO 与 NIO
java·后端
Jesse_EC3 小时前
我给消息推送加了 Publisher Confirm,然后亲手引入了一个竞态
java
S3rein3 小时前
JAVA多线程手撕
java·多线程
用户8181870627463 小时前
第7章 死锁排查实录:jstack定位死锁的完整流程
java·后端