springboot 调用外部接口方法

文章介绍了如何在Java项目中通过Mavenpom文件引入OkHttp库,并展示了如何使用它实现GET和POST请求,包括GET天气数据和POST登录请求的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入pom文件

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

请求方法get

@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请求

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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值