使用HTTP POST向GCM发送通知

时间:2014-04-07 15:27:34

标签: android http-post google-cloud-messaging

我正在尝试向Google Cloud Messaging发送HTTP POST通知,以便将通知发送到我正在开发的应用。

出于测试目的,我也从应用程序中提供HTTP POST - 只是为了看看我是否能得到响应(稍后将实现此逻辑服务器端)。

我正在按照here找到的教程,但由于我没有使用JSON,因此很难遵循。当我运行下面的代码时,我得到了预期的响应:Unauthorized: Error 401。这是因为我没有提供足够的数据,但似乎无法发现我需要使用此请求发送哪些数据。

class RequestTask extends AsyncTask<String, String, String>
    {
        final static String API_KEY = ***********; // From google developer console
        final static String CONTENT_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";
        @Override
        protected String doInBackground(String... uri)
        {
            String responseString = "";
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(uri[0]);
            try
            {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                // not even sure if "Authorization" is the correct key to send
                nameValuePairs.add(new BasicNameValuePair("Authorization", "key=" + API_KEY));
                nameValuePairs.add(new BasicNameValuePair("Content-Type", CONTENT_TYPE));
                HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
                post.addHeader(entity.getContentType());
                post.setEntity(entity);

                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String line = "";
                while ((line = rd.readLine()) != null)
                {
                    Log.i("HTTP RESPONSE", line);
                    responseString = responseString + "\n" + line;
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            return responseString;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            Intent intent = new Intent(ctx, ResponseActivity.class);
            intent.putExtra("text", result);
            startActivity(intent);
        }
    }

为了成功发送此GCM通知请求,我必须更改哪些内容?

2 个答案:

答案 0 :(得分:1)

@Eran提出的内容外,其他可能的问题可能是错误地设置了HTTP标头的Content-Type。尝试替换此行:

post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

有了这个:

HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);

然后:

post.addHeader(entity.getContentType());
post.setEntity(entity);

答案 1 :(得分:0)

这是您的错误:

nameValuePairs.add(new BasicNameValuePair("Authorization", API_KEY));

应该是:

nameValuePairs.add(new BasicNameValuePair("Authorization", "key="+API_KEY));
  

HTTP标头必须包含以下标头:

Authorization: key=YOUR_API_KEY
Content-Type: application/json for JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text.