[Spring Boot]Rest服务调用远程Post请求
pom
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
格外增加一个工具方法,处理JSON
<!-- HuTool工具库-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.28</version>
</dependency>
config类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* Rest服务
* 便捷访问远程Http服务
*
* @author fir
*/
@Configuration
public class ResTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
//超时设置
//ms
factory.setReadTimeout(120000);
//ms
factory.setConnectTimeout(120000);
return factory;
}
}
业务类-Post方法调用
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
/**
* <p>
* 网络信息数据获取 前端控制器
* </p>
*
* @author fir
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Resource
private RestTemplate restTemplate;
@GetMapping("/a")
public String bodyList() {
log.info("[Http服务]调用中...");
String url = "http://127.0.0.1:22225/toReportAlarm";
// 请求参数
HashMap<String, Object> map = new HashMap<>();
map.put("informList", "test");
//请求头处理
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Authorization", "token");
httpHeaders.add("accept", "application/json");
httpHeaders.add("Content-Type", "application/json");
// 请求参数构建
HttpEntity<String> fromEntity = new HttpEntity<>(JSONUtil.toJsonStr(map), httpHeaders);
try {
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, fromEntity, String.class);
log.info("[Http服务]返回值:" + responseEntity.getBody());
log.info("[Http服务]调用成功!");
} catch (ResourceAccessException e) {
log.info("[Http服务]调用失败,无法连接到服务器 {}", url);
}
return null;
}
}
原文地址:https://blog.csdn.net/qq_46554590/article/details/140092279
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!