Java 在RestTemplate中使用令牌
我想使用此RestTemplate代码进行POST请求Java 在RestTemplate中使用令牌,java,resttemplate,Java,Resttemplate,我想使用此RestTemplate代码进行POST请求 @Bean(name = "simpleRestTemplate") public RestTemplate getRestClient() { RestTemplate restClient = new RestTemplate(getClientHttpRequestFactory()); restClient.getInterceptors().add(new BasicAuthorizati
@Bean(name = "simpleRestTemplate")
public RestTemplate getRestClient() {
RestTemplate restClient = new RestTemplate(getClientHttpRequestFactory());
restClient.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
HttpEntity<PaymentTransaction> request = new HttpEntity<>(new PaymentTransaction());
ResponseEntity<PaymentTransaction> response = restClient.exchange("http://example.com", HttpMethod.POST,
request, PaymentTransaction.class);
PaymentTransaction foo = response.getBody();
return restClient;
}
@Bean(name=“simpleRestTemplate”)
公共RestTemplate getRestClient(){
RestTemplate restClient=新的RestTemplate(getClientHttpRequestFactory());
restClient.getInterceptors().add(新的BasicAuthorizationInterceptor(“用户名”、“密码”));
HttpEntity请求=新的HttpEntity(new PaymentTransaction());
ResponseEntity response=restClient.exchange(“http://example.com“,HttpMethod.POST,
请求,PaymentTransaction.class);
PaymentTransaction foo=response.getBody();
返回客户;
}
如何将Toke身份验证添加到HTTP链接中
可能最简单的方法是使用exchange(“http://example.com“+”/“+令牌,HttpMethod.POST,
有更好的方法吗?查看:
然后可以使用将URI
作为其第一个参数的
restClient.exchange(uri, HttpMethod.POST, request, PaymentTransaction.class);
退房:
然后可以使用将URI
作为其第一个参数的
restClient.exchange(uri, HttpMethod.POST, request, PaymentTransaction.class);
正如@nickb所评论的,身份验证最好在HTTP头中完成 如果确实需要在URL中注入令牌,可以实现自定义拦截器 伪代码:
最终字符串tokenValue=“something”;
restClient.getInterceptors().add(新的ClientHttpRequestInterceptor()){
@凌驾
ClientHttpResponse拦截(HttpRequest请求,
字节[]正文,
ClientHttPrequesteExecution执行)
抛出java.io.IOException{
URI modifiedUri=UriComponentsBuilder.fromUri(request.getURI())
.query(“标记={tokenPlaceholder}”)
.buildAndExpand(令牌值)
.toUri();
setURI(modifiedUri);
}
});
不这样做的原因有很多,例如:
正如@nickb所评论的,身份验证最好在HTTP头中完成 如果确实需要在URL中注入令牌,可以实现自定义拦截器 伪代码:
最终字符串tokenValue=“something”;
restClient.getInterceptors().add(新的ClientHttpRequestInterceptor()){
@凌驾
ClientHttpResponse拦截(HttpRequest请求,
字节[]正文,
ClientHttPrequesteExecution执行)
抛出java.io.IOException{
URI modifiedUri=UriComponentsBuilder.fromUri(request.getURI())
.query(“标记={tokenPlaceholder}”)
.buildAndExpand(令牌值)
.toUri();
setURI(modifiedUri);
}
});
不这样做的原因有很多,例如:
OAuth令牌信息?因为它会在标题中。您的示例看起来像是要将路径段添加到请求URI。您要查找的是什么?我想将路径段添加到请求URI。OAuth令牌信息?因为它会在标题中。您的示例看起来像是要添加路径segm请求URI的ent。您要查找哪一个?我想在请求URI中添加一个路径段。