如何在伪客户端(尤其是HTTP标头)中传递标头?

时间:2019-01-22 10:39:00

标签: java spring-boot spring-cloud-feign

我尝试了Rest Template传递http标头,并按预期方式工作,但有些方法无法与伪装客户端一起使用。

其他客户端代码:-

import org.springframework.http.HttpHeaders;

RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.set("appsecret-proof", header);
HttpEntity<?> request = new HttpEntity<>(httpHeader);
String url = "https://localhost/groups/{pathVariable}/members/";
Map<String, String> map = new HashMap<>();
map.put("pathVariable", pathVariable);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                                                   .queryParam("token", token);
String uriBuilder = builder.build().toString();

ResponseEntity<MemberObject> responseEntity = restTemplate.exchange(uriBuilder, HttpMethod.POST, request,MemberObject.class, map);

MemberObject memberObject = null;
if (responseEntity != null && responseEntity.getBody() != null) {
    memberObject = responseEntity.getBody();
}

主要客户代码:-

import org.springframework.web.bind.annotation.RequestHeader;

@PostMapping(value = "/groups/?token=xyz")
MemberObject getMemberGroup(@RequestHeader("appsecret-proof") String appsecretProof);

但是fegin客户给出的错误为:

{"error":{"message":"Authentication credentials could not be found.","type":"Authentication Error","code":404,"sub_code":0}}.

在伪装客户端中对令牌进行了硬编码,仍然给出相同的错误。标头可能是错误的。...有关在伪装客户端中设置标头的任何建议。

1 个答案:

答案 0 :(得分:0)

如果您使用的是Feign,这就是构造电话的方式:

import feign.Headers;
import feign.Param;
import feign.RequestLine;
...
@RequestLine("POST /groups/?token={appSecretProof}")
@Headers("Content-Type: application/json")
MemberObject getMemberGroup(@Param("appSecretProof") String appSecretProof);

在以上代码段中,在执行时将 appSecretProof 的值替换为URL,作为 token 的相应值。