You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发:使用RestTemplate调用API传递Date并处理响应

使用RestTemplate的execute方法传递Date参数并处理节假日响应

首先,先修正你提供的模型类的语法错误(类名不能有空格、关键字大小写规范),并补充必要的构造器和Getter/Setter(RestTemplate反序列化需要):

import java.util.Date;

public class CalendarHoliday {
    private Date calendar_date;
    private String description;

    // RestTemplate反序列化必须的无参构造器
    public CalendarHoliday() {}

    // Getter & Setter
    public Date getCalendar_date() {
        return calendar_date;
    }

    public void setCalendar_date(Date calendar_date) {
        this.calendar_date = calendar_date;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

RestTemplate的execute方法完全支持传递Date参数(通常需要格式化为API要求的字符串格式),并自定义响应处理逻辑,以下是完整实现示例:

1. 配置RestTemplate(Spring项目中)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

2. 使用execute方法实现需求

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StreamUtils;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Date;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;

public class HolidayChecker {

    @Autowired
    private RestTemplate restTemplate;

    public void checkIfHoliday(Date targetDate) {
        // 1. 将Date格式化为API要求的字符串格式(示例用yyyy-MM-dd,根据实际API调整)
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormatter.format(targetDate);

        // 2. API请求地址,{date}为URL参数占位符
        String apiUrl = "http://your-api-domain/holiday/check?date={date}";

        // 3. 调用execute方法发送请求并处理响应
        CalendarHoliday holidayResponse = restTemplate.execute(
                apiUrl,
                HttpMethod.GET,
                // 请求回调:可自定义请求头、请求体(GET请求无需请求体,传null即可)
                request -> request.getHeaders().setContentType(MediaType.APPLICATION_JSON),
                // 响应提取器:自定义响应处理逻辑
                response -> {
                    if (!response.getStatusCode().is2xxSuccessful()) {
                        return null; // 非成功响应直接返回null
                    }
                    // 读取响应体内容
                    String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
                    if (StringUtils.isEmpty(responseBody)) {
                        return null; // 响应为空无需处理
                    }
                    // 将响应体反序列化为CalendarHoliday对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.setDateFormat(dateFormatter); // 匹配API返回的日期格式
                    return objectMapper.readValue(responseBody, CalendarHoliday.class);
                },
                formattedDate // 填充URL参数
        );

        // 4. 处理结果
        if (holidayResponse != null && holidayResponse.getCalendar_date() != null) {
            System.out.printf("日期[%s]是节假日:%s%n", 
                    dateFormatter.format(holidayResponse.getCalendar_date()),
                    holidayResponse.getDescription());
        } else {
            // 响应为空或无有效日期,无需处理
            System.out.printf("日期[%s]不是节假日或无响应%n", formattedDate);
        }
    }
}

关键注意事项

  • Date参数传递:API一般不直接接受Date对象,必须格式化为符合要求的字符串(如ISO8601、yyyy-MM-dd等),避免序列化格式错误。
  • 响应处理灵活性:execute方法的响应提取器允许你完全自定义逻辑,包括判断响应体是否为空、反序列化对象、处理异常状态码等,完全匹配你的需求。
  • 模型类规范:必须提供无参构造器,否则RestTemplate无法完成反序列化;如果API返回的字段名与模型类变量名不匹配,可添加@JsonProperty("字段名")注解做映射。
  • 异常处理:可根据需求在方法中捕获HttpClientErrorException、HttpServerErrorException等异常,处理API调用失败的场景。

内容的提问来源于stack exchange,提问作者HinataDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:39:16