java使用RestTemplate封装post请求方式

网友投稿 663 2022-09-19


java使用RestTemplate封装post请求方式

目录使用RestTemplate封装post请求RestTemplate使用封装1、SpringBoot使用RestTemplate(使用apache的httpclient)2、使用jdk原生的2、拦截器实现ClientHttpRequestInterceptor4、常用的方法

使用RestTemplate封装post请求

之前笔者写过一篇比较实用的文章 java使用httpclient封装post请求和get的请求,其实java中实现http请求还可以用 RestTemplate 完成,下面给出示例代码:

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.http.*;

import org.springframework.http.converter.StringHttpMessageConverter;

import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

import java.nio.charset.Charset;

public class HttpHelper {

private static Logger logger = LoggerFactory.getLogger(HttpHelper.class);

private RestTemplate restTemplate;

private HttpHeaders httpHeaders;

@PostConstruct

public void init() {

restTemplate = new RestTemplate();

restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

httpHeaders = new HttpHeaders();

httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

}

/**

* post - json

* @param params

* @return

*/

public String post(JSONObject params, String url) {

logger.info("请求参数:{}", params.toJSONString());

ResponseEntity response;

try {

response = restTemplate.exchange(

url,

HttpMethod.POST,

new HttpEntity<>(params, httpHeaders),

String.class);

} catch (Exception e) {

logger.error("请求异常", e);

return "请求异常";

}

logger.info("响应结果:{}", JSONObject.toJSONString(response));

if (response.getStatusCode().equals(HttpStatus.OK)) {

logger.info("请求成功,返回结果:{}", response.getBody());

return response.getBody();

}

logger.error("请求失败,Http状态码:{},返回结果:{}", response.getStatusCode(), response.getBody());

return response.getBody();

}

}

RestTemplate 是 Spring 提供的用于访问Rest服务的客户端,RestTemplate 提供了多种便捷访问远程Http 服务的方法,能够大大提高客户端的编写效率。

RestTemplate使用封装

之前接口调用习惯性使用HttpClient,代码复杂,冗余代码多,关心资源回收用起来不是很爽。

RestTemplate默认依赖jdk的HTTP连接工具。也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty、OkHttp。

1、SpringBoot使用RestTemplate(使用apache的httpclient)

import org.springframework.boot.web.client.RestTemplateBuilder;

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.http.converter.ByteArrayHttpMessageConverter;

import org.springframework.http.converter.FormHttpMessageConverter;

import org.springframewqTDuwork.http.converter.HttpMessageConverter;

import org.springframework.http.converter.ResourceHttpMessageConverter;

import org.springframework.http.converter.StringHttpMessageConverter;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;

import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.TimeUnit;

@Configuration

public class RestTemplateConfig {

@Bean

public RestTemplate getRestTemplate() {

//手动指定转换器(HttpMessageConverter)

List> messageConverters = new ArrayList>();

messageConverters.add(new ByteArrayHttpMessageCohttp://nverter());

messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));//string强制使用UTF-8

messageConverters.add(new ResourceHttpMessageConverter());

messageConverters.add(new AllEncompassingFormHttpMessageConverter());

messageConverters.add(new FormHttpMessageConverter());

MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();

jacksonConverter.getObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

messageConverters.http://add(jacksonConverter);

RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(messageConverters).build();

restTemplate.setRequestFactory(getClientHttpRequestFactory());

return restTemplate;

}

@Bean

public ClientHttpRequestFactory getClientHttpRequestFactory() {

// 保持长连接配置,需要在头添加Keep-Alive

final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {

@Override

public long getKeepAliveDuration(org.apache.http.HttpResponse response, HttpContext context) {

// 设置一个链接的最大存活时间

return 5 * 1000L;

}

};

PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);

pollingConnectionManager.setMaxTotal(2000);//最大连接数

pollingConnectionManager.setDefaultMaxPerRoute(200);//同路由的最大连接数

CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setConnectionManager(pollingConnectionManager).setKeepAliveStrategy(myStrategy).build();

HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(closeableHttpClient);

factory.setConnectTimeout(3000);

factory.setReadTimeout(5000);

return factory;

}

}

2、使用jdk原生的

// 添加消息转换器

List messageConverters = new ArrayList();

messageConverters.add(new StringHttpMessageConverter());

messageConverters.add(new MappingJackson2HttpMessageConverter());

//如果useJ2SEHttp申明为true,则使用JDK自带的HttpURLConnection

SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

requestFactory.setReadTimeout(3000);

requestFactory.setConnectTimeout(3000);

restTemplate = new RestTemplate(requestFactory);

restTemplate.setMessageConverters(messageConverters);

//这里是添加了拦截器

List interceptorList = new ArrayList();

interceptorList.add(new RequestInteceptor());

restTemplate.setInterceptors(interceptorList);

2、拦截器实现ClientHttpRequestInterceptor

(设置头信息的时候回使用到)

public class RequestInteceptor implements ClientHttpRequestInterceptor {

@Override

public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

request.getHeaders().setAll(AppMetadataUtil.getAPP_METADATA());

String traceId = UUID.randomUUID().toString().replaceAll("-", "");

request.getHeaders().set("TraceId", traceId.toString());

return execution.execute(request, body);

}

}

4、常用的方法

String url = queryInfo?userId={userId}&pageIndex={pageIndex}&pageSize={pageSize}";

HashMap parameterMap = new HashMap();

parameterMap.put("userId", userId);

parameterMap.put("pageIndex", pageIndex);

parameterMap.put("pageSize", pageSize);

String str = restTemplate.getForObject(url, String.class, parameterMap);

String result = restTemp.getForObject(requestUrl.toString(), String.class);

//post

String url = "http://xxx.com/queryInfo"

String str = restTemplate.postForObject(url, parameterMap, String.class);

//exchange 设置请求头

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));

headers.add("Accept", "application/json;charset=UTF-8");

HttpEntity httpEntity = new HttpEntity("", headers);

RestTemplate restTemplate = RestTemplateUtils.getInstance().getRestTemplate();

ResponseEntity exchange = restTemplate.exchange(retailOrderUrl, HttpMethod.GET, httpEntity, String.class);

String forObject = exchange.getBody();

MultiValueMap requestEntity = new LinkedMultiValueMap<>();


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:华为设备配置IS-IS的路由聚合(基于华为路由器的基本静态路由配置示例)
下一篇:华为设备配置IS-IS基本功能(华为存储iscsi连接配置)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~