RequestParams params.put method doesn't receive integer - java

I'm using Rest service to get a list of States of a Country (countryid) from database. The service runs well in Tomcat but it doesn't run in Android. Below is the code to invoke the Rest service. The params.put("countryid",countryID) method doesn't receive integer. Could you please help me over come this issue?
public void getDataForStateSpinner(){
//new StateSpinnerAsync().execute();
System.out.println("getDataForStateSpinner(), spnCountry adapter: " + spnCountry);
System.out.println("spnCountry.getSelectedItem(): " + spnCountry.getSelectedItem());
if (spnCountry.getSelectedItem()!=null){
System.out.println("getDataForStateSpinner(), spnCountry adapter isn't empty");
final Country country = (Country) spnCountry.getSelectedItem();
int countryID = country.getCountryID();
RequestParams params = new RequestParams();
if (countryID>=0){
params.put("countryid", countryID);
invokeWS_State(params);
} else{
Toast.makeText(mParent.get(), "Can not get CountryID", Toast.LENGTH_LONG).show();
}
}
}
public void invokeWS_State(RequestParams params){
System.out.println("Inside invokeWS_State");
AsyncHttpClient client = new AsyncHttpClient();
System.out.println("Inside invokeWS_State, client: " + client);
System.out.println("Inside invokeWS_State onSuccess, params: " + params);
client.get(stateURL, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String respond){
try{
System.out.println("Inside invokeWS_State onSuccess, stateURL: " + stateURL);
System.out.println("Inside invokeWS_State onSuccess, respond:" + respond);
JSONArray jsonArr = new JSONArray(respond);
//JSONObject jsonObject = jsonArr.getJSONObject(0);
System.out.println("Inside invokeWS_State onSuccess jsonArr:" + jsonArr);
String stateList = jsonArr.toString();
System.out.println("Inside invokeWS_State onSuccess stateList:" + stateList);
states = (ArrayList<State>) fromJasonToJava_State(stateList);
for (State state : states) {
System.out.println("State id: " + state.getStateID() + " name: " + state.getStateName());
}
spnStateAdapter = new ArrayAdapter<State>(mParent.get(), android.R.layout.simple_spinner_dropdown_item, states);
spnStateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnState.setAdapter(spnStateAdapter);
} catch (JSONException e){
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content){
String resultString = null;
if (statusCode == 404){
resultString = "Requested resource not found";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
resultString = "Something went wrong at server end!";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
} else {
resultString = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
}
}
});
}
And below is the Rest service which runs well in Tomcat:
#Path("/State")
public class StatesResource {
#GET
#Path("/GetStates")
#Produces(MediaType.APPLICATION_JSON)
//http://localhost:8080/com.fms.FMSRestfulWS/State/GetStates?countryid=1
public String getStates(#DefaultValue("1") #QueryParam("countryid") int countryID){
String states = null;
try{
ArrayList<State> feedData = null;
StateLoading stateLoading = new StateLoading();
feedData = stateLoading.getAllStatesForCountry(countryID);
Gson gson = new Gson();
states = gson.toJson(feedData);
}catch (Exception e){
System.out.println("System Error " + e);
}
return states;
}
}

Do only one change, it will work perfect.
params.put("countryid", ""+countryID);

Related

Google Play in-app Billing onPurchasesUpdated() error response code -1

I've been implementing for the first time in-app billing in my app and even if all the code is correct, it is not working!
I have a BillingManager.java
public class BillingManager implements PurchasesUpdatedListener {
private static final String TAG = "BillingManager";
private final BillingClient mBillingClient;
private final Activity mActivity;
String base64Key = "mykey";
private static Context myCxt;
private String mAdRemovalPrice;
private static final String ITEM_SKU_ADREMOVAL = "myskuid";
public int billingResult;
public BillingManager(Activity activity) {
mActivity = activity;
mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponse) {
if (billingResponse == BillingClient.BillingResponse.OK) {
Log.i(TAG, "onBillingSetupFinished() good response: " + billingResponse);
List skuList = new ArrayList<>();
skuList.add(ITEM_SKU_ADREMOVAL);
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK
&& skuDetailsList != null) {
for (Object skuDetailsObject : skuDetailsList) {
SkuDetails skuDetails = (SkuDetails) skuDetailsObject;
String sku = skuDetails.getSku();
String price = skuDetails.getPrice();
if (ITEM_SKU_ADREMOVAL.equals(sku)) {
mAdRemovalPrice = price;
}
}
}
}
});
} else {
Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
}
}
#Override
public void onBillingServiceDisconnected() {
Log.w(TAG, "onBillingServiceDisconnected()");
}
});
}
#Override
public void onPurchasesUpdated(int responseCode, List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for(Purchase purchase: purchases) {
// When every a new purchase is made
// Here we verify our purchase
Log.i(TAG, "onPurchasesUpdated() ourchase ok response: " + responseCode);
if (!verifyValidSignature(purchase.getOriginalJson(), purchase.getSignature())) {
// Invalid purchase
// show error to user
myCxt = MainActivity.proContext;
Toast.makeText(myCxt, myCxt.getString(R.string.purchase_err), Toast.LENGTH_LONG).show();
Log.i(TAG, "Got a purchase: " + purchase + "; but signature is bad. Skipping...");
return;
} else {
// purchase is valid
// Perform actions
myCxt = MainActivity.proContext;
Toast.makeText(myCxt, myCxt.getString(R.string.purchase_done), Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(myCxt);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isPro", true);
editor.apply();
}
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
Log.i(TAG, "onPurchasesUpdated() user canceled response: " + responseCode);
} else {
// Handle any other error codes.
Log.i(TAG, "onPurchasesUpdated() error response: " + responseCode);
}
}
public void startPurchaseFlow() {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku(ITEM_SKU_ADREMOVAL)
.setType(BillingClient.SkuType.INAPP)
.build();
mBillingClient.launchBillingFlow(mActivity, flowParams);
Log.i(TAG, "StartPurchaseFlow called");
}
private boolean verifyValidSignature(String signedData, String signature) {
try {
return Security.verifyPurchase(base64Key, signedData, signature);
} catch (IOException e) {
Log.e(TAG, "Got an exception trying to validate a purchase: " + e);
return false;
}
}
And then i call it like this in my App menu:
if (id == R.id.action_pro) {
BillingManager mbilling = new BillingManager(MainActivity.this);
mbilling.startPurchaseFlow();
return true;
}
Actually it turns out that if I read the logs in debugging mode seems that onPurchasesUpdated() method throws the error -1 as response code! So this means that the responsecode is -1 which according to Java documentation is a generic error in http protocol... Why am I getting this?
The code seems pretty good even if compared to others or to guides found online. Does anyone have any suggestions?
Please make sure your billing client is initialized before you start the purchaseflow.
response code -1 indicates billingclient disconnected

Sending push notifications to multiple devices using FCM, SQL, java

I have a work service which sending push notifications to the registration device and it works well, but I have a problem sending push notifications to multiple devices. I'm trying to use loops but it doesn't help. I think that to count the responses maybe give me results. Maybe the problem in the boolean expression, I don't guess. Maybe somebody knows what to do in this situation. Thanks for response and code below:
#RequestMapping(value = "/sendtodeviceid", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> send() throws JSONException, SQLException {
try {
System.out.println("\n" + "send massege to devicesid" + "\n" + "start to get ID" + "\n");
ArrayList <String> deviceList = new ArrayList<>();
Statement statement = jdbcService.getStatement();
String selSql = String.format("SELECT deviceid FROM courier WHERE isActive = true");
ResultSet rs = statement.executeQuery(selSql);
// check equals for more deviceid
while (rs.next()) {
String deviceid = rs.getString("deviceid");
System.out.println("DEVAICE ID which true from sending message " + "\n" + deviceid + "\n");
deviceList.add(deviceid);
if (!deviceid.equals(deviceid)) {
String newdeviceid = deviceid;
deviceList.add(newdeviceid);
}
}
System.out.println(deviceList + "\n");
// find some solution for loop sending message to all device
for (String iddevice: deviceList) {
System.out.println("DEVICE ID: " + iddevice + "\n");
// create jsonObject look like this
// {
// "data":
// {"address":"latitude420&longitude420",
// "click_action":".MessageOrder",
// "order":"#420"},
// "to":
// "d2Hxxa6PNYw",
// "priority":"high"
// },{}
do {
JSONObject body = new JSONObject();
body.put("to", iddevice);
body.put("priority", "high");
// JSONObject notification = new JSONObject();
// notification.put("title", "Wise delivery");
// notification.put("body", "It is personal order!!!");
// notification.put("icon", "main_logo_black");
// notification.put("click_action", ".MessageOrder");
JSONObject data = new JSONObject();
data.put("order", "#421");
data.put("address", "latitude420&longitude421");
data.put("click_action", ".MessageOrder");
// data.put("icon","main_logo_black");
// body.put("notification", notification);
body.put("data", data);
HttpEntity<String> request = new HttpEntity<>(body.toString());
System.out.println("JSON file request" + request);
CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} while (iddevice == null);
}
} catch (SQLException e) {
System.out.println("don't selectSQL" + "\n" + "SELECT deviceid FROM courier ");
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
And terminal shows this:
// start
send message to devicesid
start to get ID
// get device id from database
DEVAICE ID which true from sending message
d2Hxxa6PNYw:
DEVAICE ID which true from sending message
eb0s9KRXac8:
// create the ArrayList
[d2Hxxa6PNYw, eb0s9KRXac8]
// and at this step I have a problem
DEVICE ID: d2Hxxa6PNYw
JSON file request<{"data":{"address":"latitude420&longitude421",
"click_action":".MessageOrder",
"order":"#421"},
"to":"d2Hxxa6PNYw",
"priority":"high"},{}>
// after this must be the next step in loop)
Instead of using a loop, you can subscribe users to a specific topic. Then you can send notifications using Firebase Console or writing server-side logic.
FirebaseMessaging.getInstance().subscribeToTopic("news")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = getString(R.string.msg_subscribed);
if (!task.isSuccessful()) {
msg = getString(R.string.msg_subscribe_failed);
}
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
My friend helped me and all working well
#RequestMapping(value = "/sendtodeviceid", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> send() throws Exception {
System.out.println("\n" + "send massege to devicesid" + "\n" + "start to get ID" + "\n");
ArrayList<String> deviceList = new ArrayList<>();
Statement statement = jdbcService.getStatement();
String selSql = String.format("SELECT deviceid FROM courier WHERE isActive = true");
ResultSet rs = statement.executeQuery(selSql);
while (rs.next()) {
String deviceid = rs.getString("deviceid");
System.out.println("DEVAICE ID which true from sending message " + "\n" + deviceid + "\n");
deviceList.add(deviceid);
if (!deviceid.equals(deviceid)) {
String newdeviceid = deviceid;
deviceList.add(newdeviceid);
}
}
System.out.println(deviceList + "\n");
List<CompletableFuture> sentNotifications = new ArrayList<CompletableFuture>();
for (String deviceId : deviceList) {
HttpEntity<String> request = new HttpEntity<>(_buildRequestJsonBody(deviceId).toString());
CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
sentNotifications.add(pushNotification);
}
CompletableFuture.allOf(sentNotifications.toArray(new CompletableFuture[sentNotifications.size()])).join();
for (CompletableFuture<String> notification : sentNotifications) {
String firebaseResponse = notification.get();
System.out.println("RESPONSE " + firebaseResponse);
return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
private JSONObject _buildRequestJsonBody(String deviceId) {
JSONObject body = new JSONObject();
body.put("to", deviceId);
body.put("priority", "high");
JSONObject data = new JSONObject();
data.put("order", "#421");
data.put("address", "latitude420&longitude421");
data.put("click_action", ".MessageOrder");
body.put("data", data);
return body;
}
}

Cant access success function when call recursive ajax

I'm building a system which has push notification feature and use Jersey to create API.
I read an article about comet approach and end up with the following code:
Index.js
function checkExamNotification() {
$.ajax({
url: contextPath + '/api/notification/checkExamNotification',
type: 'get',
data: {
accountId: accountId,
sessionId: sessionId
},
success: function (res) {
console.log("success");
displayNumberOfNotification();
checkExamNotification();
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus === "timeout") {
checkExamNotification();
}
}
});
}
$(document).ready(function () {
$.ajaxSetup({
timeout: 1000*60*3
});
checkExamNotification();
});
Check exam notification API
#GET
#Path("/checkExamNotification")
public Response checkExamNotification(#QueryParam("accountId") int accountId, #QueryParam("sessionId") String sessionId) throws InterruptedException {
if (memCachedClient.checkSession(sessionId, accountId)) {
while (!examNotificationQueue.hasItems()) {
Thread.sleep(5000);
}
ExamNotificationQueueItemModel examNotificationQueueItemModel = examNotificationQueue.dequeue();
if (examNotificationQueueItemModel.getAccountId() == accountId) {
LOGGER.info("[START] Check exam notification API");
LOGGER.info("Account ID: " + accountId);
LOGGER.info("Get notification with exam ID: " + examNotificationQueueItemModel.getExamId());
ExamEntity exam = examDAO.findById(examNotificationQueueItemModel.getExamId());
NotificationEntity notification = notificationDAO.findByExamId(exam.getExamid());
notification.setSend(1);
notificationDAO.getEntityManager().getTransaction().begin();
notificationDAO.update(notification);
notificationDAO.getEntityManager().getTransaction().commit();
LOGGER.info("[END]");
String result = gson.toJson(examNotificationQueueItemModel);
return Response.status(200).entity(result).build();
} else {
examNotificationQueue.enqueue(examNotificationQueueItemModel);
Thread.sleep(5000);
checkExamNotification(accountId, sessionId);
}
}
return Response.status(200).entity(gson.toJson("timeout")).build();
}
From my debug, the API did finish return but the success event SOMETIMES didn't fire.
Yes, sometimes console log success but sometimes it doesn't.
Can anybody explain to me this case?
Thanks in advance. Any help would be appreciated.
Ok after following #peeskillet comment. Here is my finally code.
Check exam notification API
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
#Path("/checkExamNotification")
public EventOutput checkExamNotification(#QueryParam("accountId") final int accountId, #QueryParam("sessionId") final String sessionId) {
final EventOutput eventOutput = new EventOutput();
if (memCachedClient.checkSession(sessionId, accountId)) {
new Thread(new Runnable() {
public void run() {
try {
if (examNotificationQueue.hasItems()) {
ExamNotificationQueueItemModel examNotificationQueueItemModel = examNotificationQueue.dequeue();
if (examNotificationQueueItemModel.getAccountId() == accountId) {
LOGGER.info("[START] Check exam notification API");
LOGGER.info("Account ID: " + accountId);
LOGGER.info("Get notification with exam ID: " + examNotificationQueueItemModel.getExamName());
String result = gson.toJson(examNotificationQueueItemModel);
final OutboundEvent.Builder eventBuilder
= new OutboundEvent.Builder();
eventBuilder.data(result);
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
LOGGER.info("[END]");
} else {
examNotificationQueue.enqueue(examNotificationQueueItemModel);
}
}
} catch (IOException e) {
throw new RuntimeException(
"Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (IOException ioClose) {
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
}
}).start();
}
return eventOutput;
}
Index.js
function checkExamNotification() {
var url = contextPath + '/api/notification/checkExamNotification?accountId=' + accountId + '&sessionId=' + sessionId;
var source = new EventSource(url);
source.onmessage = function (event) {
displayNumberOfNotification();
};
}

QuickBooks NULL CallbackHandler

I'm trying to perform a batch operation in QuickBook but getting null callbackhandler.
private static void AddBulkCustomer(DataService ds) throws FMSException{
BatchOperation bo = new BatchOperation();
Customer c1 = new Customer();
c1.setGivenName("Customer 3");
c1.setDisplayName("Disp Customer 3");
EmailAddress email = new EmailAddress();
email.setAddress("customer1#zzz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b3");
c1= null;
c1 = new Customer();
c1.setGivenName("Customer 4");
c1.setDisplayName("Disp Customer 4");
email = null;
email = new EmailAddress();
email.setAddress("customer2#z2zz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b4");
// String strQuery = " select * from customer where givenname ='"+c1.getGivenName()+"'";
// bo.addQuery(strQuery, "b3Query");
ds.executeBatchAsync(bo, new AsyncCallBackBatch());
}
For AsyncCallback operation
public class AsyncCallBackBatch implements CallbackHandler {
#Override
public void execute(CallbackMessage callbackMsg) {
System.out.println("asyncCallbackBatch is executing... ");
try {
System.out.println("QR = "+callbackMsg.getFMSException().toString());
BatchOperation BO = callbackMsg.getBatchOperation();
if (BO != null) {
List<String> bId = BO.getBIds();
for (String strBId : bId) {
if (BO.isFault(strBId)) {
Fault fault = BO.getFault(strBId);
System.out.println("asyncCallBackBatch Error Code : "+ fault.getError().get(0).getCode() + " "+ "Error : "
+ fault.getError().get(0).getDetail()+ ", Message : "+ fault.getError().get(0).getMessage());
} else if (BO.isEntity(strBId)) {
System.out.println("Batch having entity message.. ");
Customer cust = (Customer) BO.getEntity(strBId);
System.out.println("cust id : " + cust.getId()+ " CustName = " + cust.getGivenName());
} else if (BO.isQuery(strBId)) {
System.out.println("Batch having Query ... Parsing... ");
QueryResult qR = BO.getQueryResponse(strBId);
System.out.println("Query : " + qR.getTotalCount());
} else if (BO.isReport(strBId)) {
System.out.println("Batch having Report... ");
Report report = BO.getReport(strBId);
System.out.println(" " + report.getClass().getName());
} else {
System.out.println("Something went wrong... ");
}
}
}else{
System.out.println("Batch Operation terminated, reason: NULL callbackMsg ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
OAuthAuthorizer oAuth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
//403352746
try {
Context context = new Context(oAuth, ServiceType.QBO, "403352746");
System.out.println("RealmID : "+context.getRealmID());
context.setCustomerRequestTimeout(99999);
System.out.println("TimeOut Set to = "+context.getCustomerRequestTimeout());
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
DataService ds = new DataService(context);
AddBulkCustomer(ds);
System.out.println("Operation Complete..");
} catch (Exception e) {
e.printStackTrace();
}
}
When I debug, in execute method, I'm getting Null BatchOperation in return. I'm not sure performing Batch operation is allowed in sandbox environment.
I found the solution after so much of testing and communication with Quickbooks Devs thought would be helpful for others.
In sandbox environment even if you set the config properties to sandbox URL it still picks as PROD URL in Callbackhandler.
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
In this case they called this as a bug, currently all you can do is to make a trial account in PROD and then test this.

GCM Client in Java not working

I want to create an android GCM sender which will send the URL to the Android app. I have used this windows application to test my android app and it is working. I checked the code in C# and tried to convert it in Java. But I am not getting anything. Let me know what I am missing.
import java.util.*;
import java.util.logging.Logger;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;
//import org.apache.http.HttpResponse;
import org.apache.http.*;
import org.apache.http.util.EntityUtils;
public class Client {
String device_id;
String api_id;
String Msg;
String ResultJSON;
private String GCM_URI = "https://android.googleapis.com/gcm/send";
HttpURLConnection gcmRequest = null;
HttpResponse gcmResponse = null;
Client()
{
//default constructor...do nothing
}
Client(String dev, String auth)
{
this.device_id = dev;
this.api_id = auth;
}
public String Send(String message) throws IOException
{
// Escape condition
if (device_id == null || api_id == null)
{
return "[ERROR] Device Token or API Key has not been set";
}
InitGCMClient();
PostPayload(message);
/*gcmResponse = (HttpResponse) gcmRequest.getResponseMessage();
catch (WebException we)
{
return "[ERROR] There is a problem within processing GCM message \n" + we.Message;
}*/
try {
System.out.println(gcmRequest);
ResultJSON = gcmRequest.getResponseMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResultJSON;
}
public String ReadResponse(HttpResponse response)
{
//StreamReader responseReader = new StreamReader(response.GetResponseStream());
//return responseReader.ReadToEnd();
try {
String responseString = EntityUtils.toString(response.getEntity());
return responseString;
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void InitGCMClient()
{
URL obj = null;
try {
obj = new URL(GCM_URI);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
gcmRequest = (HttpURLConnection) obj.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
gcmRequest.setRequestProperty("Content-Type", "application/json");
gcmRequest.setRequestProperty("User-Agent", "Android GCM Message Sender Client 1.0");
gcmRequest.setRequestProperty("Authorization", "key=" + api_id);
try {
gcmRequest.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void PostPayload(String message) throws IOException
{
String payloadString = AssembleJSONPayload(device_id, message);
byte[] payloadByte = payloadString.getBytes("UTF-8");
//gcmRequest.ContentLength = payloadByte.length;
String len = new String(payloadByte);
gcmRequest.setRequestProperty("Content-Length", len);
gcmRequest.setDoOutput(true);
gcmRequest.setDoInput(true);
OutputStream payloadStream = gcmRequest.getOutputStream();
payloadStream.write(payloadByte, 0, payloadByte.length);
payloadStream.close();
}
public String AssembleJSONPayload(String gcmDeviceToken, String gcmBody)
{
String payloadFormatJSON =
"{{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {{" +
" " + gcmBody + " " +
"}}" +
"}}";
String payload = String.format(payloadFormatJSON, gcmDeviceToken, gcmBody);
//Debug.WriteLine("payload : " + payload);
System.err.println("payload : " + payload);
return payload;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String dev = "<device_ID>";
String auth = "<api_ID>";
Client cl = new Client(dev, auth);
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("\nSend your msg\n");
String msg = sc.nextLine();
cl.Send(msg);
}
}
}
I just started working on Android. So kindly let me know if there are any relevant suggestions as well.
Input:
"key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg"
In Console, I am getting:
payload : {{"registration_ids" : ["device_id"],"data" : {{ "key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg" }}}}
EDIT
Your payload message inside AssembleJSONPayload is not formatted correctly. Please use following code to build payload:
String payloadFormatJSON =
"{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {" +
" " + gcmBody + " " +
"}" +
"}";
Output should be:
payload : {"registration_ids" : ["gcmDeviceToken value"],"data" : {"gcmBody value"}}

Categories

Resources