RestTemplate

RestTemplate
package com.ssdl.advertise.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.ssdl.advertise.dto.req.SendDaPingReqDto;
import com.ssdl.advertise.service.MessageDaPinService;
import com.ssdl.advertise.util.TimeUtils;

import lombok.extern.log4j.Log4j2;

/**
 * 发送信息给大屏 有图片才发送给大屏
 * @author Administrator
 */
@Service
@Log4j2
public class MessageDaPinServiceImpl implements MessageDaPinService{

	@Value("${kht.daPingUrl}")
	private String daPingUrl;
	@Autowired
    private RestTemplate restTemplate;
	
	@Override
	public void sendDaPing(String brandName, String biEndTime, String imageUrl, String licenseNo) {
		SendDaPingReqDto sendDaPingRequest = new SendDaPingReqDto();
		sendDaPingRequest.setCity("上海市");
		sendDaPingRequest.setStoreName("海宝养车");// 门店名称
		sendDaPingRequest.setBrandName(brandName);// 品牌型号
		sendDaPingRequest.setBiEndTime(biEndTime);// 保险到期时间(商业险)
		sendDaPingRequest.setScanTime(TimeUtils.format(new Date(), TimeUtils.yyyy_MM_dd_HH_mm_ss));// 扫描时间
		sendDaPingRequest.setImageUrl(imageUrl);//
		sendDaPingRequest.setLicenseNo(licenseNo);//
		log.info("推送到大屏的请求参数:" + sendDaPingRequest);
		try {		
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			HttpEntity<String> formEntity = new HttpEntity<String>(JSONObject.toJSONString(sendDaPingRequest), headers);
			ResponseEntity<String> res = restTemplate.postForEntity(daPingUrl, formEntity, String.class);
			log.info("推送到大屏的返回参数:" + res.getBody());
		} catch (Exception e) {
			log.error("推送到大屏报错:", e);
			e.printStackTrace();
		}
	}

}

### Spring RestTemplate 使用示例与常见问题解决方法 Spring `RestTemplate` 是一个同步的 HTTP 客户端,用于简化与 RESTful 服务的交互。以下是关于其使用方法和常见问题的详细说明。 #### 1. RestTemplate 的基本用法 以下是一个简单的代码示例,展示如何使用 `RestTemplate` 进行 GET 和 POST 请求: ```java import org.springframework.web.client.RestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); // 示例 1: 发送 GET 请求并获取响应 String url = "https://jsonplaceholder.typicode.com/posts/1"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); System.out.println("GET Response Body: " + response.getBody()); // 示例 2: 发送 POST 请求 String postUrl = "https://jsonplaceholder.typicode.com/posts"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); String jsonPayload = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; HttpEntity<String> requestEntity = new HttpEntity<>(jsonPayload, headers); ResponseEntity<String> postResponse = restTemplate.exchange( postUrl, HttpMethod.POST, requestEntity, String.class ); System.out.println("POST Response Body: " + postResponse.getBody()); } } ``` 上述代码展示了如何通过 `RestTemplate` 执行 HTTP 请求,并处理响应内容[^4]。 #### 2. 常见问题及解决方法 - **问题 1**: `RestTemplate` 在 Spring Boot 2.3+ 中被标记为过时。 解决方案:从 Spring Boot 2.3 开始,官方推荐使用 `WebClient` 替代 `RestTemplate`,因为 `WebClient` 提供了非阻塞式的支持。然而,如果需要继续使用 `RestTemplate`,可以通过手动实例化或自定义配置来实现[^5]。 - **问题 2**: 如何处理请求超时? 解决方案:可以通过设置 `RequestFactory` 来调整超时时间。例如: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; public class RestTemplateTimeoutExample { public static RestTemplate createRestTemplate() { RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) // 设置连接超时时间为 5 秒 .setSocketTimeout(5000) // 设置读取超时时间为 5 秒 .build(); CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(config) .build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); } } ``` - **问题 3**: 如何处理异常? 解决方案:可以使用 `ResponseErrorHandler` 或者捕获 `RestClientException` 来处理异常。例如: ```java import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestClientException; public class RestTemplateErrorHandlingExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); try { String url = "https://nonexistent-url"; String response = restTemplate.getForObject(url, String.class); System.out.println(response); } catch (RestClientException e) { System.err.println("Error occurred: " + e.getMessage()); } } } ``` #### 3. Maven 依赖配置 为了在项目中使用 `RestTemplate`,需要确保引入了正确的 Spring 依赖。以下是一个典型的 Maven 配置示例[^2]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 如果需要额外的功能支持(如 JSON 处理),可以添加以下依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值