简体   繁体   English

从 java rest API 调用 rest API

[英]Call rest API from java rest API

I have a java rest API hosted on JBoss which call another rest webservice:我有一个托管在 JBoss 上的 java rest API,它调用另一个 rest webservice:

@GET
@Path("/testDeployment")
@Produces(MediaType.TEXT_PLAIN)
public String testDeployment() {
        URL url = new URL(restURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer "+sessionId);

        System.out.println("sessionId>>>> "+sessionId);
        System.out.println("restURL>>>> "+restURL);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            response += output; 
        }

        conn.disconnect();
}

But I am getting error但我收到错误

Server returned HTTP response code: 401 for URL: https://cs5.salesforce.com/services/apexrest/event/search?type=init服务器返回 HTTP 响应代码:401 URL: https ://cs5.salesforce.com/services/apexrest/event/search?type=init

13:16:08,738 ERROR [stderr] (default task-26) java.io.IOException: Server returned HTTP response code: 401 for URL: https://cs5.salesforce.com/services/apexrest/event/search?type=init 13:16:08,738 错误 [stderr](默认任务 26)java.io.IOException:服务器返回 HTTP 响应代码:401 用于 URL: https ://cs5.salesforce.com/services/apexrest/event/search?type =初始化

13:16:08,747 ERROR [stderr] (default task-26) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840) 13:16:08,747 错误 [stderr](默认任务 26)在 sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)

The following is the extract from the definition of Http Status Code Definitions , which might help you to solve the problem:以下是Http Status Code Definitions定义的摘录,可能会帮助您解决问题:

401 Unauthorized 401未经授权

The request requires user authentication.该请求需要用户身份验证。 The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource.响应必须包括一个 WWW-Authenticate 头字段(第 14.47 节),其中包含适用于所请求资源的质询。 The client MAY repeat the request with a suitable Authorization header field (section 14.8).客户端可以使用合适的授权头字段(第 14.8 节)重复请求。 If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.如果请求已包含授权凭据,则 401 响应表示已拒绝对这些凭据进行授权。 If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.如果 401 响应包含与先前响应相同的质询,并且用户代理已经尝试过至少一次身份验证,那么应该向用户呈现响应中给出的实体,因为该实体可能包含相关诊断信息。 HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" HTTP 访问认证在“HTTP 认证:基本和摘要式访问认证”中解释

I did add the Authorization Header:我确实添加了授权标头:

conn.setRequestProperty("Authorization", "Bearer "+sessionId); conn.setRequestProperty("授权", "承载"+sessionId);

But it looks like the header needed to be formatted, I updated the line to:但看起来标题需要格式化,我将行更新为:

conn.setRequestProperty("Authorization", String.format("Bearer %s", sessionId)); conn.setRequestProperty("Authorization", String.format("Bearer %s", sessionId));

And it worked, I guess over the web it needs to be formatted and for a java application the above code works well它起作用了,我想在网络上它需要格式化,对于 java 应用程序,上面的代码运行良好

what ever URL you are hitting is Authorized, so have to use authorization in header then you will get output as你点击的 URL 是授权的,所以必须在标头中使用授权,然后你将得到输出

1. if you are using jersey then use syntax as below:- 1. 如果您使用的是球衣,则使用如下语法:-

try{
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8085/getStepsCount");
webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
String authorization = "PASTE_KEY_HERE";
webResource.setProperty("Authorization", authorization);
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js);
String jsonString = webResource.get(String.class);}catch (Exception e){System.out.println (e.getMessage());}

and if you are using Spring Rest Controller then use this one.......如果您使用的是 Spring Rest Controller,那么请使用这个……

@RequestMapping(value = "/getStepsUsingPostRequest", method = RequestMethod.POST)
public ResponseEntity<Object> getDiscountUsingPost(
        @RequestBody MemberStepsDto memberStepsDto) {
    try{
    final String uri = "http://localhost:8085/getStepsCount";
    RestTemplate restTemplate = new RestTemplate();
    System.out.println("starting.......");
    String json = "{\"memberId\": \""+memberStepsDto.getMemberId()+"\",\"startDate\": \""+memberStepsDto.getStartDate()+"\",\"endDate\": \""+memberStepsDto.getEndDate()+"\"}";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON); 
    HttpEntity<String> entity = new HttpEntity<String>(json,headers);

    String answer = restTemplate.postForObject(uri, entity, String.class);
    System.out.println("String : " + answer);
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
    return new ResponseEntity<Object>(new String("Fetched Successfully"),HttpStatus.OK);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM