目录
- GET请求
- POST请求
依赖
简易配置
使用到的json输出工具类
public class JsonUtil {
/**
* 美化输出
*/
public static void prettyPrint(Object obj) {
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
发起GET请求
输出结果
详细配置
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// 连接超时时间
factory.setConnectTimeout(150 * 1000); // 150s
// 数据读取超时时间
factory.setReadTimeout(150 * 1000); // 150s
return factory;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
GET请求
可以替换url上的变量
输出结果
{
"args" : {
"age" : "18",
"name" : "Tom"
},
"headers" : {
"Accept" : "application/json, application/*+json",
"Host" : "httpbin.org",
"User-Agent" : "Java/1.8.0_361",
"X-Amzn-Trace-Id" : "Root=1-667bae21-22fba9c27d6e844a13c3da48"
},
"origin" : "1.202.253.34",
"url" : "https://httpbin.org/get?name=Tom&age=18"
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
POST请求
输出结果
{
"args" : { },
"data" : "{\"name\":\"Tom\",\"age\":18}",
"files" : { },
"form" : { },
"headers" : {
"Accept" : "application/json, application/*+json",
"Content-Length" : "23",
"Content-Type" : "application/json",
"Host" : "httpbin.org",
"User-Agent" : "Java/1.8.0_361",
"X-Amzn-Trace-Id" : "Root=1-667bae9e-7b8e49815c7afb9f5019b5a4"
},
"json" : {
"age" : 18,
"name" : "Tom"
},
"origin" : "1.202.253.34",
"url" : "https://httpbin.org/post"
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
参考文章
- Springboot之restTemplate配置及使用