当前位置: 代码迷 >> 综合 >> RestTemplate 和 httpClient 请求接口
  详细解决方案

RestTemplate 和 httpClient 请求接口

热度:92   发布时间:2024-02-13 07:46:33.0

RestTemplate

获取模板更改默认参数

public class RestTemplateUtil {public static RestTemplate getRestTemplate() {StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();messageConverters.add(stringHttpMessageConverter);messageConverters.add(new FormHttpMessageConverter());return new RestTemplate(messageConverters);}}

POST请求

RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
RequestBo requestBo = new RequestBo(SERVICE1, THREE_YEAR);
String s = JSONObject.toJSONString(requestBo);
HttpEntity<String> httpEntity = new HttpEntity<String>(s, httpHeaders);
URI uri = new URI("http://10.13.136.129:8082/reflectionTest");
String s1 = restTemplate.postForObject(uri, httpEntity, String.class);
System.out.println(s1);

GET请求

 RestTemplate restTemplate = new RestTemplate();URI uri = new URI(env.getProperty("api.indicator.auth.token")+ "?appKey=" + env.getProperty("tokenparams.appkey")+ "&appSecret=" + env.getProperty("tokenparams.appsecret")+ "&loginName=" + env.getProperty("tokenparams.loginname"));String rtn = restTemplate.getForObject(uri, String.class);

httpClient

POST请求

Map<String, String> headers = getHeaders();
String url = laiyeUrl + creatUser;
Map<String, String> map = new HashMap<>(16);
map.put("avatar_url", "");
map.put("nickname", userId);
map.put("user_id", userId + "_" + clientId);
String json = "";
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(JsonUtils.toJson(map), Charset.forName("UTF-8"));
httpPost.setEntity(entity);
try (CloseableHttpResponse execute = httpClient.execute(httpPost)) {HttpEntity httpEntity = execute.getEntity();json = EntityUtils.toString(httpEntity, "UTF-8");log.info(":" + json);
} catch (Exception e) {log.error("" + e.getMessage());
}

GET请求

        String response = null;logger.debug("baidu get:{}", url);HttpGet httpGet = new HttpGet(url);httpGet.setHeader("accept", "application/json");httpGet.setHeader("Content-type", "application/json");try (CloseableHttpResponse tinetResponse = httpClient.execute(httpGet)) {logger.debug( response.getStatusLine().getStatusCode());HttpEntity httpEntity = response.getEntity();response = EntityUtils.toString(httpEntity, "UTF-8");logger.debug(" response :{}", response);} catch (IOException e) {logger.error("get method asr to tinet io exception", e);}';
  相关解决方案