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();
        }
    }
}
相关推荐
z小天才b20 分钟前
Java 设计模式完全指南:从入门到精通
java·开发语言·设计模式
烤麻辣烫25 分钟前
算法--二分搜索
java·开发语言·学习·算法·intellij-idea
逍遥德37 分钟前
MQTT教程详解-03. 高级知识点
java·物联网·中间件·信息与通信·iot·iotdb
Nice__J1 小时前
ISO26262功能安全——SafeOS
java·linux·安全
夹芯饼干1 小时前
虚拟机指令第六节
java·linux·服务器
A_aspectJ1 小时前
【Java基础开发】基于 Java Swing +MySQL + JDBC 版实现图书管理系统
java·开发语言·mysql
TE-茶叶蛋1 小时前
Spring最核心扩展点:BeanPostProcessor
java·后端·spring
Mr.45671 小时前
SpringBoot多模块依赖冲突排查与架构优化实战(避坑指南)
java·spring boot·架构
学术阿凡提1 小时前
Spring Boot 优雅实现异步调用:从入门到自定义线程池与异常处理
java·数据库·算法
我是无敌小恐龙2 小时前
Java SE 零基础入门Day06 方法重载+Debug调试+String字符串全套API详解(超全干货)
java·开发语言·人工智能·python·transformer·无人机·量子计算