Spring中封装的通过Java代码发送RestFul请求的模板类,内置发送get post delete等请求的方法,
在SpringBoot中只要导入spring-boot-starter-web的依赖可以直接使用。
登录后复制
/**
* RestTemplate配置
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// 超时设置
factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
}
Get请求方式:
url拼接参数
url拼接参数「占位符的方式」
获取响应实体对象「响应状态码」
登录后复制
@Autowired
private RestTemplate restTemplate;
/**
* 测试get请求
*/
@Test
public void test1(){
/**
* getForObject
*
* 参数1 要请求的地址的url 必填项
* 参数2 响应数据的类型 是String 还是 Map等 必填项
* 参数3 请求携带参数 选填
*
* getForObject 方法的返回值就是 被调用接口响应的数据
*/
String result = restTemplate.getForObject("http://localhost:8802/testRestGet?username=zhangsan", String.class);
System.out.println(result);
/**
* getForEntity 方法
* 参数1 要请求的地址的url 必填项
* 参数2 响应数据的类型 是String 还是 Map等 必填项
* 参数3 请求携带参数 选填
*
* 返回值类型为 ResponseEntity
*
* 可以通过ResponseEntity 获取响应的数据,响应的状态码等信息
*/
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8802/testRestGet?username=zhangsan", String.class);
System.out.println("获取响应的状态:"+responseEntity.getStatusCode());
System.out.println("获取响应的数据:"+responseEntity.getBody());
/**
* 通过Map传参
*/
Map map= new HashMap();
map.put("name","zhangsan");
String resultId = restTemplate.getForObject("http://localhost:8802/testRestGet?username={name}",
String.class,map);
System.out.println(resultId);
}
post请求三种情况
模拟携带表单参数
url拼接参数
请求成功之后,获取跳转地址
登录后复制
/**
* 测试Post请求
*/
@Test
public void test2(){
/**
* postForObject 返回值为响应的数据
* 参数1 要请求地址的url
* 参数2 通过LinkedMultiValueMap对象封装请求参数 模拟表单参数,封装在请求体中
* 参数3 响应数据的类型
*/
LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<>();
request.set("username","zhangsan");
String result = restTemplate.postForObject("http://localhost:8802/testRestPost",request,String.class);
System.out.println(result);
/**
* Post请求的时候同样也可以进行参数拼接,使用方式和Get一样
* 示例如下,通过map封装数据,利用占位符的方式可以将参数拼接到url上
* 和Get请求url拼接一样
*/
Map map = new HashMap();
map.put("password","123456");
String result2 = restTemplate.postForObject("http://localhost:8802/testRestPost?password={password}",request,
String.class,map);
/**
* postForLocation 这个API和前两个都不一样
*
* 登录or注册都是post请求,而这些操作完成之后呢?大部分都是跳转到别的页面去了,这种场景下,就可以使用 postForLocation 了,提交数据,并获取返回的URI
* 响应参数要跳转的地址
*/
URI uri = restTemplate.postForLocation("http://localhost:8802/testRestPostLocation", request);
System.out.println("postForLocation请求到的地址为:"+uri);
}
登录后复制
package com.lby;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
/**
* @author luxiaoyang
* @create 2020-03-20-20:37
*/
public class UserAgentInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
// 设置请求头参数
headers.add(HttpHeaders.USER_AGENT,
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
return execution.execute(request, body);
}
}
然后
登录后复制
/**
* 通用方式设置请求头
*/
@Test
public void test3(){
/**
* RestTemplate设置使用请求头的拦截器
*/
restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor()));
/**
* 正常的发送请求
*/
String result = restTemplate.getForObject("http://localhost:8802/testRestGet?username=zhangsan", String.class);
System.out.println(result);
}
Post请求的第二个参数是Request,可以根据请求头 + 请求参数,构建 HttpEntity 对象,将这个作为post的请求request参数传入
登录后复制
/**
* Post方式设置请求头
*/
@Test
public void test4(){
//1. 设置请求头参数
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
//2. 模拟表单参数 请求体携带参数
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("username", "zhangsan");
//3. 封装HttpEntity对象
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
//4. 发送Post请求
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8802/testRestPost", requestEntity, String.class);
System.out.println(responseEntity.getBody());
}
登录后复制
//1. 设置请求头参数
HttpHeaders headers = new HttpHeaders();
// 设置请求头参数
headers.add("content-type","application/x-www-form-urlencoded");
//2. 模拟表单参数 请求体携带参数
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("grant_type","password");
requestBody.add("username","admin");
requestBody.add("password","kubeSphere123");
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, headers);
RestTemplate restTemplate = new RestTemplate();
//4. 发送Post请求
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://36.111.131.38:22246/oauth/token", requestEntity, String.class);
System.out.println(responseEntity.getBody());
登录后复制
RestTemplate restTemplateGet = new RestTemplate();
HttpHeaders headersGet = new HttpHeaders();
headersGet.add("Content-Type","application/json");
headersGet.add("Authorization",token);
HttpEntity<String> entity = new HttpEntity<String>(null, headersGet);
ResponseEntity<String> result = restTemplateGet.exchange("http://36.111.128.2:22246/kapis/monitoring.kubesphere.io/v1alpha3/cluster?metrics_filter=cluster_cpu_usage|cluster_cpu_total|cluster_cpu_utilisation|cluster_memory_usage_wo_cache|cluster_memory_total|cluster_memory_utilisation|cluster_disk_size_usage|cluster_disk_size_capacity|cluster_disk_size_utilisation|cluster_pod_running_count|cluster_pod_quota$", HttpMethod.GET, entity, String.class);
/**
* 正常的发送请求
*/
System.out.println(result.getBody());
四种方法试试
登录后复制
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(ConnectTimeoutConstant.connectTimeout);
httpRequestFactory.setConnectTimeout(ConnectTimeoutConstant.connectTimeout);
httpRequestFactory.setReadTimeout(ConnectTimeoutConstant.connectTimeout);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
//第四种方案 {"name":"item_full_title","value":"2020夏季新款女款连衣裙修身V领连衣裙韩版chic中长裙子"}
restTemplate.getMessageConverters().clear();
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
//第一种尝试方案,{"name":"item_full_title","value":"2020\u590f\u5b63\u65b0\u6b3e"}
// restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//第二种尝试方案{"name":"item_full_title","value":"2020\u590f\u5b63\u65b0\u6b3e"}
// List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
// httpMessageConverters.stream().forEach(httpMessageConverter -> {
// if(httpMessageConverter instanceof StringHttpMessageConverter){
// StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
// messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
// }
// });
//第三种尝试方案,{"name":"item_full_title","value":"2020\u590f\u5b63\u65b0\u6b3e"}
// StringHttpMessageConverter t = new StringHttpMessageConverter();
// //设置为false就可以修改header中的accept-charset属性
// t.setWriteAcceptCharset(false);
// t.setDefaultCharset(StandardCharsets.UTF_8);
// restTemplate.getMessageConverters().add(0,t);
return restTemplate;
依赖
登录后复制
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
登录后复制
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
public static String getHttpResult(String url, JSONObject jsonParm) {
String result = null;
String forecast_url = url;
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建post请求方法实例对象
PostMethod postMethod = new PostMethod(forecast_url);
// 设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
String toJson = jsonParm.toString();
System.out.println(toJson);
try {
RequestEntity se = new StringRequestEntity(toJson, "application/json", "UTF-8");
postMethod.setRequestEntity(se);
int httpStatus = httpClient.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
} catch (Exception e) {
postMethod.releaseConnection();
}
postMethod.releaseConnection();
return result;
}
原网址: 访问
创建于: 2024-12-13 09:59:32
目录: default
标签: 无
未标明原创文章均为采集,版权归作者所有,转载无需和我联系,请注明原出处,南摩阿彌陀佛,知识,不只知道,要得到
最新评论