试图HTTP-POST从Java GCM(Trying to HTTP-POST to GCM fr

2019-11-02 23:33发布

我想要一个HTTP-POST发送到谷歌云消息传递服务。 我已经安装了正确的按键,一切工作时我使用PHP脚本发送推送通知到我的手机。

但我的Java httpPost只返回一个401响应。 我已按照给出的说明Android开发者 ,但我仍然得到了烦人的401我错了分配头字段?

我的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

    public class Server {
      public static void main(String[] args) throws IOException {

          String url = "https://android.googleapis.com/gcm/send";

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);


            HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");

            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("registration_id=", "MY_DEVICE_GSM_REG_ID"));
            urlParameters.add(new BasicNameValuePair("data=", "Type=value,Lat=58.365547,Long=8.613235,Comment=value"));

            httppost.setHeader("Authorization",
                    "key=MY_API_AUTH_FROM_GOOGLE_API_CONSOLE_BROWSER_TOKEN");
            httppost.setHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");

            post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));

            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " 
                        + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
}
}

Answer 1:

您是否正确设置Authorization头。 有可能是你的API密钥的问题。

你有你的注册ID和有效载荷的问题(这是不相关的401错误)。

这是错误的:

urlParameters.add(new BasicNameValuePair("registration_id=", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data=", "Type=value,Lat=58.365547,Long=8.613235,Comment=value"));

您应该删除=从密钥和每个有效载荷参数应该启动data. 。 因此,你应该有:

urlParameters.add(new BasicNameValuePair("registration_id", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data.Type", "value"));
urlParameters.add(new BasicNameValuePair("data.Lat", "58.365547"));
urlParameters.add(new BasicNameValuePair("data.Long", "8.613235"));
urlParameters.add(new BasicNameValuePair("data.Comment", "value"));


文章来源: Trying to HTTP-POST to GCM from Java