解析:在 REST 中未经授权 API

Parse: Unauthorized in REST API

我正在尝试从使用 Jersey 的 Parse REST API 的 Java 代码发送推送通知。

    Client client = Client.create();

    WebResource webResource = client.resource("https://api.parse.com/1/push");

    //My real id instead of XXXXXXXXXXXXXXXXXXXXXXXX    
    webResource.header("X-Parse-Application-Id", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

    //My real key instead of XXXXXXXXXXXXXXXXXXXXXXXX 
    webResource.header("X-Parse-REST-API-Key", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

    Map<String, Object> postData = new LinkedHashMap<>();
    postData.put("channels", Arrays.asList("")); //Broadcast notification

    Map<String, String> notificationData = new LinkedHashMap<>();
    notificationData.put("alert", "This is a notification");

    postData.put("data", notificationData);

    //Convert POST data to String
    String postDataAsStr = "";
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        postDataAsStr = objectMapper.writeValueAsString(postData);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    ClientResponse response = webResource
                    .accept(MediaType.APPLICATION_JSON)
                    .type(MediaType.APPLICATION_JSON)
                    .post(ClientResponse.class, postDataAsStr);

POST 数据如下:

{"channels":[""],"data":{"alert":"This is a notification"}}

但我得到:

{"error":"unauthorized"}

看来您还需要添加 "Authorization" header。

webResource.header("Authorization", String.format("Negotiate %s", createTicket())

createTicket() 的实现取决于您的授权方法。

已解决。我以这种方式添加了 headers:

 ClientResponse response = webResource
                .accept(MediaType.APPLICATION_JSON)
                .header("X-Parse-Application-Id", "XXXXXXXXXXXXXXXXXXXXXXXXXX")
                .header("X-Parse-REST-API-Key", "XXXXXXXXXXXXXXXXXXXXXXXXX")
                .type(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, postDataAsStr);