简体   繁体   中英

Call rest API from java rest API

I have a java rest API hosted on JBoss which call another 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

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,747 ERROR [stderr] (default task-26) at 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:

401 Unauthorized

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. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. 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. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication"

I did add the Authorization Header:

conn.setRequestProperty("Authorization", "Bearer "+sessionId);

But it looks like the header needed to be formatted, I updated the line to:

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

what ever URL you are hitting is Authorized, so have to use authorization in header then you will get output as

1. if you are using jersey then use syntax as below:-

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.......

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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