2013-01-14 55 views
1

我嘗試使用Google Cloud Messaging通知用戶有新數據從服務器接收。發送使用GCM消息被定義爲:來自應用程序的GCM POST

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

是否有可能發送從Android應用此HTTP 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

是否可以從android應用程序發送此HTTP POST請求?

這是我在GCMintent類中發佈用戶註冊的所有相關設備信息的方式。希望這有助於回答你的問題,我不是100%你正在嘗試做什麼tbh。

@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。

相關問題