2015-01-27 1 views
0

Я использую этот код для отправки push-уведомления на устройствах Android. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Его работы. Но они используют php на стороне сервера. и мой сервер - JAVA. поэтому я пытаюсь создать для этого тестирование jUnit. поэтому мой сервер отправит push-уведомление. Но я не знаю об этом. Я попробовал метод post, но не работал. получив ошибку 401.Как отправить push-уведомление сервером с помощью тестирования jUnit

Строка regID = "";

 pairs.add(new BasicNameValuePair("registration_ids",regID)); 
     pairs.add(new BasicNameValuePair("data","test")); 
     pairs.add(new BasicNameValuePair("key","my key")); 

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

     String data = makePostCall(url, pairs); 

Просьба предложить мне в jUnit.

ответ

0

Я передавал неправильные параметры. Это должен быть заголовок и тело. Это способ, которым я пользовался и работал хорошо.

public class SendPushNotification { 

public static void main(String[] arg){ 
    PushNotification pushNoti = new PushNotification(); 

    //collect the device_tokens into JSONArray. 
    // device_tokens is the tokens of user where we needs to send the push Messages. 

    String id = "APA9******WVWA"; 

    JSONArray deviceTokenArray = new JSONArray(); 
    // if you want to send more than one device then you have to 
    // add more ids into JSONArray by using put method. 
    deviceTokenArray.put(id); 
    try { 
     pushNoti.sentPushIntoAndroid(deviceTokenArray, "I Love to my sister and sending a push message in Android Device"); 

    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

, а это еще один класс, который использует HTTPHeader и HTTPBody.

public class PushNotification { 

public void sentPushIntoAndroid(JSONArray device_token, String message) 
     throws JSONException { 


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

    StringEntity stringentity = new StringEntity(generateJSONBodyForHTTPBody(device_token, message).toString(), "UTF-8"); 

    httppost.addHeader("Content-Type", "application/json"); 
    httppost.addHeader("Authorization", "key=AI**********Mo""); 

    httppost.setEntity(stringentity); 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httppost); 

     HttpEntity entity = response.getEntity(); 

     String strresponse = null; 
     if (entity != null) { 
      strresponse = EntityUtils.toString(entity); 

      displayLog("HTTP Response ", strresponse); 
     } 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

private JSONObject generateJSONBodyForHTTPBody(JSONArray device_token, String message) throws JSONException { 

    JSONObject jObj = new JSONObject(); 
    jObj.put(CommonUtilities.REGISTRATION_ID, device_token); 

    JSONObject dataJson = new JSONObject(); 

//NOTE:- In Client side, you have to retrieve below param by using getBundle().getString("id") like it. so it will retrieve the id and do for other params too like as i did for id. 
    dataJson.put("id", "testingID"); 
    dataJson.put("type", "testingType"); 
    dataJson.put("imglink", "testingimgLink"); 
    dataJson.put("seolink", "testingseoLink"); 
    dataJson.put("msg", "Lata Bhulli"); 

    jObj.put("data", dataJson); 

    displayLog("JSONObject", jObj.toString()); 

    return jObj; 
} 

private void displayLog(String tag, String message) { 
    System.out.println(tag+" "+message); 
} 

Примечание: - Если вы получаете ошибку компиляции, чем вы должны использовать последнюю HTTP Библиотеку и используемую в LIBS папки затем добавить все в пути сборки.