spring调用第三方接口

本文详细介绍了HTTP请求的多种方法,包括POST、GET、PUT和DELETE,展示了如何使用Java进行JSON和表单数据的发送,以及如何处理实体和参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

post请求

  • content-type:json
userData.put("accountid", "-1");
//设置请求头
HttpHeaders headers = new HttpHeaders();      
headers.add("Accept", "application/json");
headers.add("Content-Type", contentType);
//userData 是请求体body
HttpEntity<Object> entity = new HttpEntity<>(userData, headers);

ResponseEntity resp = HttpUtil.restTemplate.exchange(请求url, HttpMethod.POST, entity, Object.class);
						
  • content-type:application/x-www-form-urlencoded
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
postParameters.put("param1", Collections.singletonList(param1));

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
HttpEntity<Object> entity = new HttpEntity<>(postParameters, headers);

ResponseEntity responseEntity = HttpUtil.restTemplate.exchange(hangupUrl, HttpMethod.POST, entity, Object.class);
  • postForEntity、postForObject、postForLocation同getForEntity。

get请求

  • getForEntity
//第一种
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://uri?name={1}", String.class, "张三");

//第二种
Map<String, String> map = new HashMap<>();
map.put("name", "李四");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://uri?name={name}", String.class, map);
//第三种
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://uri?name={name}").build().expand("王五").encode();
URI uri = uriComponents.toUri();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
  • getForObject同getForEntity

put请求

restTemplate.put("http://uri/{1}", book, 99);

delete请求

restTemplate.delete("http://uri/{1}", 100);
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值