sending GCM message in java - java

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();
}
}

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>.

Related

How to send push notification by serverside using jUnit testing

I am using this code for sending push notification in Android devices. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Its work. But they are using php in server side. and My Server side is JAVA. so I am trying to create jUnit testing for that. so my server will send push notification. But i have not idea about that. I tried by post method but did not work. getting 401 error.
String 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);
Please suggest to me in jUnit.
I was passing incorrect params. It should be header and body. This is way which I used and working nice.
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();
}
}
and that is another class which is using HTTPHeader and 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);
}
Note:- If you are getting compile error than you have to use latest HTTP Libraries and used in libs folder then add all in build path.

Put POST request with HttpRequest

I'm making a google login through GoogleTransport and ClientLogin.
private final GoogleTransport transport = new GoogleTransport();
private final ClientLogin authenticator = new ClientLogin();
Then I'm accessing the Picasa web api.
transport.setVersionHeader(PicasaWebAlbums.VERSION);
transport.applicationName = "google-picasaandroidsample-1.0";
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
authenticator.authTokenType = PicasaWebAlbums.AUTH_TOKEN_TYPE;
authenticator.username = StaticVariables.USER_NAME+StaticVariables.USER_DOMAIN;
authenticator.password = StaticVariables.USER_PASSWORD;
try {
authenticator.authenticate().setAuthorizationHeader(transport);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://picasaweb.google.com/data/feed/api/user/default");
request.execute();
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above is working fine.
Now I want to set a POST request. But buildPostRequest() method does not support any String parameter. So, unable to post any data at the URL. How to achieve it? Please help.
You may use HttpPost with NameValuePair
private boolean sendData(ArrayList<NameValuePair> data) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then create your Name Value pairs in a different method as
private ArrayList<NameValuePair> setupData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(USERID, SAMPLE_USER_ID);
nameValuePairs.add(new BasicNameValuePair(USERNAME, SAMPLE_USER_NAME));
return nameValuePairs;
}
Atlast call the send data method in an AsyncTask or Intent service as sendData(setupdata())
Data in a post request is usually sent in the body of the request.

Sending simple POST by HttpRequest with Android

I want my application to send two strings through the query string to a php file that will handle them as POST variables.
So far I have this code
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I think it's an easy problem to solve but it's my first android app and I'd appreciate all the help.
Use nameValuePairs to pass data in the POST request.
Try it like this :
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}

how to load picture to server using iqengines api

I am trying to recognize pictures with IQ Engines, and can't upload picture. Have anyone practice with using this api, or any ather to recognize pictures? I tryed to load bitmap, use Base64, load link to picture, but haven't always get img-this field is required. the last example of code is
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost("http://api.iqengines.com/v1.2/query/");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(path);
try {
// Add your data
String time = myTime();
String m = "api_key" + apiKey + "img" + file.getPath() + "json1"
+ "time_stamp" + time;
try {
sign = HmacSha1Signature.calculateRFC2104HMAC(m, secret);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
entity.addPart("api_key", new StringBody(apiKey));
entity.addPart("api_sig", new StringBody(sign));
entity.addPart("time_stamp", new StringBody(time));
entity.addPart("json", new StringBody("1"));
entity.addPart("img", new FileBody(file));
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
String result = EntityUtils.toString(entity1);
tv.setText(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
can anyone tell how it must be, or give working example of any other free api image recognition on android?

Android, HttpPost for WCF

I'm trying to use httpost to get data from our WCF webservice
If the webservice function is without params , something like List getAllMessages()
I'm getting the List in json, no problem here
The tricky part is when the function needs to get argument
let's say Message getMessage(string id)
when trying to call this kind of functions I get error code 500
The working code is:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
this code works great for functios without arguments..
I took this code and changed it to:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The function header in thr webservice is:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
Anyone can see what am I missing?
Thanks, I'm breaking my head over this one.
List isn't json,
try
String data = "{ id : \"" + id + "\" }";
Don't forget to set Content-Length to data.length.

Categories