You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by GitBox <gi...@apache.org> on 2019/12/30 07:23:59 UTC

[GitHub] [servicecomb-java-chassis] sunjinghan7331 edited a comment on issue #1503: 使用restTemplate调用provider接口时如何设置请求头信息

sunjinghan7331 edited a comment on issue #1503: 使用restTemplate调用provider接口时如何设置请求头信息
URL: https://github.com/apache/servicecomb-java-chassis/issues/1503#issuecomment-569602813
 
 
   > 我写过的一个方法 你可参考下 /**
   > * @param url 请求地址
   > * @param bodyParam 请求体
   > * @param headerParam 头部信息
   > * @param rClass 返回体类型
   > * @param 请求体类型
   > * @param 返回体类型
   > * @return 返回结果
   > */
   > public <T, R> R doPost(String url, T bodyParam, Map<String, String> headerParam, Class rClass) {
   > 
   > ```
   >     if (null == rClass || StringUtils.isEmpty(url)) {
   >         throw new ExecuteFailedResponse("url is empty or restTemplate is null.");
   >     }
   >     HttpHeaders requestHeaders = new HttpHeaders();
   >     if (null != headerParam) {
   >         headerParam.entrySet().forEach(entrySet -> requestHeaders.add(entrySet.getKey(), entrySet.getValue()));
   >     }
   >     HttpEntity<T> requestEntity = new HttpEntity<T>(bodyParam, requestHeaders);
   >     ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Object.class);
   > 
   >     return transforObjet(rClass, response.getBody());
   > }
   > ```
   
   我使用了你的方法,可以得到正确的返回数据,但是我无法获得这些数据。详细说明一下,在我的provider工程中,我以
   TenantResponse tenant = new TenantResponse();
   tenant.setUsername("username");
   tenant.setPassword("password");
   return Response.ok().entity(tenant).build();
   作为我的接口返回值,Response是javax.ws.rs.core中的类。
   
   在我的consumer中调用此接口,
   String token = "Basic tl3JfTTNKkii42th4b/IjA==";
           HttpHeaders requestHeaders = new HttpHeaders();
           requestHeaders.add("Authorization", token);
           HttpEntity entity = new HttpEntity(requestHeaders);
           ResponseEntity<TenantResponse> response = restTemplate.exchange("cse://user-mgmt-be/v1/users/userId", HttpMethod.GET, entity, TenantResponse.class);
   System.out.prinln(response .getBody().getUsername());
   
   由于consumer与provider是两个不同的微服务,所以TenantResponse类是在两个微服务中分别定义的,但是具有同样的字段。不过在response.getBody()时提示ClassCastException,provider的TenantResponse不能转化为consumer的TenantResponse,请问应该如何解决?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services