0
votes

I am new in Java programming. i have developed an android application which send a request to GCM server and in response its getting a registration id which i am send to my java server and on server i am storing it in database. Its working fine :)

For second part i have written http code in java server. with this code i am access the registration id from database and sending it to GCM server with a string message for for device. But i am getting error. my code for http client is here. please can some one help?

public static String REQUEST_URL = "https://android.googleapis.com/gcm/send";
private static String GCM_ID = "APA91bFEnZXT7YRTJm2d5NpbKcpJCuDwEIJjZmwYITIIWIOFIZHEtwYc8S3oN_Upe3RnSvUqcwmntIrMqaF8Vn04b_EZtvoDQMAqt21Zw9Sb9GhNXwVS70yDOjUyRohH7u1RmtTHRrkjaBUueIjS2gD1Uw1cQDJbQg";

/**
 * @param args
 */
public static void main(String[] args) {

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();

    formparams.add(new BasicNameValuePair("registration_id", GCM_ID));
    formparams.add(new BasicNameValuePair("data", "this is data mesg"));
    // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
    // "UTF-8");

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(REQUEST_URL);

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

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(formparams, "utf-8"));
        httpclient.execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
1
There is a gcm client library as part of the google/android sdk that makes sending gcm messages very easy. We use it in our back end servers to send push notifications to android devices. You should look into using that as opposed to low level http code - cmbaxter
What is the error you got ? - Bishan
@JUNAID Did you solve the problem. I have a similar problem too. - user2800040
You could use the gcm-server.jar with which you could easily implement the server side code to push messages to device. - varna

1 Answers

0
votes

I don't know what error you got, but this line :

formparams.add(new BasicNameValuePair("data", "this is data mesg"));

should be :

formparams.add(new BasicNameValuePair("data.message", "this is data mesg"));

Each payload parameter you include in the GCM message should have a name of the form data.<key>.