从java rest API调用rest API

时间:2016-05-13 07:47:47

标签: java api rest

我在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();
}

但我收到错误

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

13:16:08,738 ERROR [stderr](默认任务-26)java.io.IOException:服务器返回HTTP响应代码:401为URL:https://cs5.salesforce.com/services/apexrest/event/search?type=init

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

3 个答案:

答案 0 :(得分:2)

以下是Http Status Code Definitions定义的摘录,可能有助于您解决问题:

  

401未经授权

     

请求需要用户身份验证。响应必须包含WWW-Authenticate头字段(第14.47节),其中包含适用于所请求资源的质询。客户端可以使用合适的Authorization头字段重复请求(第14.8节)。如果请求已包含授权凭据,则401响应表示已拒绝授权这些凭据。如果401响应包含与先前响应相同的挑战,并且用户代理已经尝试过至少一次认证,则应该向用户呈现响应中给出的实体,因为该实体可能包括相关的诊断信息。 HTTP访问身份验证在“HTTP身份验证:基本和摘要访问身份验证”

中进行了说明

答案 1 :(得分:0)

我添加了授权标题:

conn.setRequestProperty(“授权”,“持票人”+ sessionId);

但看起来标题需要格式化,我将该行更新为:

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

并且它有效,我猜在网络上需要格式化,对于java应用程序,上面的代码运行良好

答案 2 :(得分:0)

您要点击的URL是授权的,因此必须在标题中使用授权,然后您将获得输出

<强> 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());}

如果你使用的是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);
}