来自应用程序的GCM POST

时间:2013-01-14 02:51:38

标签: android google-cloud-messaging

我正在尝试使用Google Cloud Messaging在有新数据从服务器接收时通知用户。使用GCM发送消息定义为:

To send a message, the application server issues a POST request to https://android.googleapis.com/gcm/send.

是否可以从Android应用程序发送此HTTP POST请求?我已经尝试使用我已成功使用的方法来实现这一点,以便POST到由MongoLab托管的服务器。我的尝试如下:

    input_json.put("registration_ids", RegistrationIDs);
    input_json.put("data", data);
    param = new StringEntity(input_json.toString());

    HttpParams httpParams = new BasicHttpParams();
    int some_reasonable_timeout = (int) (20 * DateUtils.SECOND_IN_MILLIS);
    HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
    HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);

    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost request = new HttpPost(url);
    request.setEntity(param);
    request.setHeader("Content-type", "application/json");
    request.setHeader("Authorization", API_KEY);
    HttpResponse response = httpClient.execute(request);

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() == HttpStatus.SC_OK){
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = responseHandler.handleResponse(response);
    }

我没有收到任何HTTP错误或gcm服务器的响应,所以我真的不知道从哪里开始。谢谢你的帮助。

1 个答案:

答案 0 :(得分:-1)

是否可以从Android应用程序发送此HTTP POST请求?

这是我在GCMintent类中发布有关用户注册的所有相关设备信息的方法。希望这有助于回答你的问题,我不是100%你想要做的事情。

@Override
protected void onRegistered(Context ctx, String regId) {
    // send regId to your server
    sendRegistrationIdToServer(regId, "01");    
}


public void sendRegistrationIdToServer(String registrationId, String func) {
    //Send the reg info to server
    Log.d(TAG, "Sending registration ID to my application server");
    String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);
    Context context = getApplicationContext();

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
        nameValuePairs.add(new BasicNameValuePair("func", func));
        nameValuePairs.add(new BasicNameValuePair("registrationid",registrationId));
        nameValuePairs.add(new BasicNameValuePair("app", GetPackageName()));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            Log.e("HttpResponse", line);
        }

    } catch (IOException e) {
        Log.e("HttpResponse", "broke");
    }
}

它很容易适应发送Json。