Question

I have the following DropWizard resource which is supposed to make a Google Cloud Messaging request and return the response. I keep on getting Unauthorized 401 error.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Path(value="/gcm")
@Produces(MediaType.APPLICATION_JSON)
public class GcmResource {
    Client client;

    public GcmResource(Client client) {
        this.client = client;
    }

    @GET
    public String sendMsg() {
        WebResource r = client.resource("https://android.googleapis.com/gcm/send");
        r.header("Authorization", "key=MY_SERVER_API_KEY");
        r.accept(MediaType.APPLICATION_JSON);
        r.type(MediaType.APPLICATION_JSON);

        ClientResponse res = r.post(ClientResponse.class, "{\"registration_ids\":[\"ABC\"]}");
        return res.getEntity(String.class);
    }

}
  • I am using a valid API key.
  • My API key is of type "Server (with IP blocking)".
  • I have no IPs in the block list. So, all IPs are allowed.
  • I also ran the above code from my web-hosting server, there too I get the same error.

What am I doing wrong?

Was it helpful?

Solution

Finally I found the bug in the above code. I actually wrote a PHP code to dump all Http request it receives - header and body. I changed the above code to send request to my PHP code instead. That is when I noticed that none of the headers I set were being sent! Then I noticed the bug.

I had assumed that lines like r.header("Authorization", "key=MY_SERVER_API_KEY") actually modify r. I was wrong. They return a new Builder object which has those changes. So, now the below modified version works.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Path(value="/gcm")
@Produces(MediaType.APPLICATION_JSON)
public class GcmResource {
    Client client;

    public GcmResource(Client client) {
        this.client = client;
    }

    @GET
    public String sendMsg() {
        WebResource r = client.resource("https://android.googleapis.com/gcm/send");
        ClientResponse res = r
            .header("Authorization", "key=MY_SERVER_API_KEY")
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class, "{\"registration_ids\":[\"ABC\"]}");
        return res.getEntity(String.class);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top