Spring restTemplate post请求

本文介绍了一种使用Java实现OAuth2.0认证并调用API接口的方法。首先通过发送包含appSecret和appId的请求获取access token,然后在后续的请求中将此token作为Authorization头的一部分,完成对目标接口的安全调用。

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

第一种方式 K=V

public  String getTokenValue(){
		String tokenValue = "";
		String appSecret= "1ea3aaa468d616694465ee2b924fd2a0";
		String appId = "ext-hjy";
		String prefix = "Bearer " ;
		MultiValueMap<String, String> request = new LinkedMultiValueMap<>();
		request.add("appSecret", appSecret);
		request.add("appId", appId);
		String url = "https://gw.wtoip.com/api/oauth/accessToken";
		URI uri = URI.create(url);
		Map maps = restTemplate.postForObject(uri,request, Map.class);
		String  code = maps.get("code").toString();
		if("200".equals(code)){
			String stringData = maps.get("data").toString();
			int startIndex = stringData.indexOf("=")+1;
			int endIndex = stringData.indexOf(",");
			tokenValue = stringData.substring(startIndex,endIndex);
			tokenValue = prefix +tokenValue;
		}
 
		return  tokenValue;
	}

第二种方式 object

@Override
	public Map orderCommonSubmit(Object orderCommonVoJson) {
		Map menberVoJson = new HashMap();
		menberVoJson.put("menberVoJson",orderCommonVoJson);
		//POST方式
		HttpHeaders headers = new HttpHeaders();
		String tokenValue = getTokenValue();
		//String tokenValue = "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJhcHBDb2RlXCI6XCJleHQtaGp5XCJ9IiwiZXhwIjoxNTM2MjExMTk3fQ.bK-ZesyuwV23GmsddhUxisVrVM-WuouSF8iecSymTfs";
		headers.add("Authorization",tokenValue);
		String cookie = getCookie();//获取Cookie值
		headers.add("Cookie",cookie);
		headers.add("Content-Type","application/json");
		String parameter = getParameterCommentJson();//获取参数值
		HttpEntity<Object> formEntity = new HttpEntity<Object>(parameter, headers);
		String url = "https://gw.wtoip.com/order-core/api/order/normal-submit";
		Map maps = restTemplate.postForObject(url,formEntity, Map.class);
		logger.info(maps);
		Object  data = maps.get("data");
		logger.info("开发平台返回的除会员下单数据:"+data);
		return maps;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值