Android gcm sending link testing - android

Sir,,
I would like to try my application to test push-notification by typing this link below , but it comes to trying , there is no effect.Would you please tell me what is the correct format for the hyperlink to test my Application program ?
The below is my link
https://android.googleapis.com/gcm/send?registration_ids=
APA91bHhJQJGK1OJxYHcZeH81JoAprU97CAvMHQ58cHj3MYHD204MTn1W9Kl_i51UV8ej5qwLfkwvK-vihfuWjXG6iBvkUZJuclqoNbAjx_K2mN_P2ai4rI82P0dax_tm7NHc-k_1FsBn6hvwxjxxPdgMdtYpSIdwA
&data.message="hello testing"
collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "

You can actually test it from the Android device itself:
public class PushTester {
final static private String deviceId = "YOUR_DEVICE_ID";
final static private String apiId = "YOUR_API_ID";
final static private String sendUrl = "https://android.googleapis.com/gcm/send";
static void testPush() {
URL url;
HttpsURLConnection urlConnection;
OutputStream os = null;
InputStream is = null;;
try {
url = new URL(sendUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Android Push tester");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key="+apiId);
JSONObject message = new JSONObject();
JSONArray regIds = new JSONArray();
JSONObject data = new JSONObject();
regIds.put(deviceId);
message.put("registration_ids", regIds);
//message.put("collapse_key", value)
data.put("something", "value");
message.put("data", data);
urlConnection.setDoOutput(true);
os = urlConnection.getOutputStream();
os.write(message.toString().getBytes());
os.flush();
int status = urlConnection.getResponseCode();
is = urlConnection.getInputStream();
byte[] response = new byte[4096];
is.read(response);
String responseText = String.valueOf(response);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
os = null;
is = null;
}
}
}

Related

android : converting ArrayList to JSON and post to a url

**hello dear friends ,In my project i have an arraylist that filling from beacons data every second , is it possible to convert this arrayL to JSONArray and post it to an URL at the same time ??? **
'private ArrayList<Beacon> arrayL = new ArrayList<>();
#Override
public void onBeaconServiceConnect() {
iBeaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, Region region) {
runOnUiThread(new Runnable() {
#Override
public void run() {
arrayL.clear();
arrayL.addAll((ArrayList<Beacon>) iBeacons);
}
});
}
});'
enter image description here
You could try something like that:
1) Build the JSON object
ArrayList<Beacon> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
2) Post to server
public void postData() {
ArrayList<String> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
URL url = null;
try {
url = new URL("http://www.android.com/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
for(int i = 0; i < mJSONArray.length(); i++)
{
try {
JSONObject objects = mJSONArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Iterate through the elements of the array i.
//Get thier value.
//Get the value for the first element and the value for the last element.
}
JSONObject json = new JSONObject();
byte[] outputBytes = new byte[0];
try {
outputBytes = json.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
OutputStream os = null;
try {
os = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.write(outputBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hope it helps.

Android App Crashes if no internet during server connection

I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?
My code:
public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");
request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
System.out.println("PRIINTING");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = response.getEntity().getContent();
String result = Utils.convertInputStreamToString(inputStream);
System.out.println("server response is :" + result + "\n" + inputStream);
try {
ja=new JSONArray(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
Log.e("ClientServerDemo", "Error:", e);
toastText2 = "Connection Error !";
}
return true;
}
protected void onPreExecute() {
//display the progress dialog
mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);
}
#Override
protected void onPostExecute(Boolean valid) {
mProgressHUD2.dismiss();
// if server response is successful
for(int i=0;i<ja.length();i++){
try {
jo=ja.getJSONObject(i);
db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(),
jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
new DoPOST3().execute();
}
Please help
why you don't go for httpurlconection
#Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
}
check before calling asynctask
if(Util.haveNetworkConnection(this))
{
HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
req.execute();
}

Android Socket: Read Continuous Data

I am trying to read data continuously using the following code:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
readInpt = inputStream.toString();
byteArrayOutputStream.write(buffer, 0, bytesRead);
response = byteArrayOutputStream.toString("UTF-8");
}
textResponse.setText(readInpt);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
But for some reason, it doesn't show me any output in the textbox. any help would be appreciated.
There are at least two issues in your code.
Frist, I'm not sure the method toString() on the inputStream is going to work, because the documentation says it returns a description of the object (which would be different than the string recieved). You might be confusing this with the contents of buffer which might be what you really want.
readInpt = inputStream.toString(); // Probably wrong
Second. You're updating the User Interface from a background thread, inside doInBackground() , which is always forbidden.
textResponse.setText(readInpt); // Forbidden, move somewhere else, e.g. onPostExecute()
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
response = stdIn.readLine();
publishProgress(response);
Log.i("response", response);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
catch (Exception e) {
e.printStackTrace();
}
You cannot print it on text field because the socket will listen to the server socket.If server socket does not send any response it will listen to the socket continuously until the response is received.

postexecute in asynctask is not executing

#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url3="http://www.digitalmarketingbox.com/webtool/boxdata/"+MainActivity.abc+"/updates.zip";
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
x=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
x=false;
}
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(url3).openConnection();
con.setRequestMethod("HEAD");
xc=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
xc=false;
}
//x=exists(params[0]);
//xc=exists(url3);
valve=String.valueOf(x);
if(valve.equals("true"))
{
finalurl=url+ MainActivity.abc + "/resources.zip";
filename="resources.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else if(xc==true)
{
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else
{
try
{
HttpClient client = new DefaultHttpClient();
Log.i("url for checking update",url1);
HttpPost post = new HttpPost(url1);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("reqtype", "resendcontent"));
parameters.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent;
ent = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
Log.i("url",finalurl);
}
catch (final IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
}
try{
URL url = new URL(finalurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//File SDCardRoot = Environment.getExternalStorageDirectory();
filedestination=Environment.getExternalStorageDirectory() +"/" + filename;
//File file = new File(SDCardRoot,filename);
File file = new File(filedestination);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
totalSize = urlConnection.getContentLength();
Log.i("size",String.valueOf(totalSize));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
}
catch (final IOException e) {
e.printStackTrace();
}
Log.i("download info","Download complete");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String source = Environment.getExternalStorageDirectory() + "/" + filename;
Log.i("Download destination",source);
String destination =Environment.getExternalStorageDirectory()+ "/";
Log.i("Extract destination",destination);
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
try
{
HttpClient client1 = new DefaultHttpClient();
Log.i("url is",url1);
HttpPost post1 = new HttpPost(url1);
List<NameValuePair> parameters1 = new ArrayList<NameValuePair>();
parameters1.add(new BasicNameValuePair("reqtype", "completeupdate"));
parameters1.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters1.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent1 = new UrlEncodedFormEntity(parameters1,HTTP.UTF_8);
post1.setEntity(ent1);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return foo;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stu
super.onPostExecute(result);
//result=bn;
/*if(!result.isEmpty())
{
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
Log.i("AsyncTask finish time",String.valueOf(seconds));
}*/
}
i am using this asynctask class in my activity to do some task and checking via the getstatus method that it has finished or not ,but it is never finished
above is my code of my asynctask class and its postexecute is not working can someone expalin me why?
I have also experienced the same problem. It happens when your Main UI thread goes to sleep. Try to use a timer in your UI thread to keep it awake.

how to post using HttpUrlConnection in android -> getting error : java.io.IOException: content-length promised 82 bytes, but received 43

Hello here I am trying for the post data from android to server.I am trying using HttpURLConnection.
Here I am sending username & password for Authentication for entering data for particular user in drupal. I have also tried to post data with various other methods. Using DefaultHttpClient but no luck. I am getting 401 error with using DefaultHttpClient.
Here is the link of question that I have asked on stackoverflow. Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
SO please help. Thanks for listening.
Here is my code.
public static class post_idea extends AsyncTask<Void, Void, Void> {
String strResponse1;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
public Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/user/login";
String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/node.json";
// String url = "http://mobiappdevelopers.com/drupal_test/my_android_drupal/node.json";
//String url = "http://www.drupal7.mobileapplicationtesters.com/my_services/node.json";
strResponse1 = makeWebForPostIdea(url,title,body);
System.out.println("=========> Response from post idea => "
+ strResponse1);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
}
public static String makeWebForPostIdea(String url123, String title,String body)
{
HttpURLConnection httpcon = null;
JSONObject json = null;
JSONObject jsonnode = null;
try {
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("value", body.toString());
JSONArray array = new JSONArray();
array.put(jsonvalue);
jsonnode = new JSONObject();
jsonnode.put("und", array);
System.out.println("######2 jsonnode=======>"+jsonnode.toString());
json = new JSONObject();
json.put("title",title);
json.put("body", jsonnode);
json.put("type","article");
System.out.println("value of the combine node=======>"+json.toString());
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
httpcon = (HttpURLConnection) ((new URL(url123).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
String urlParameters =
"type=" + URLEncoder.encode("page", "UTF-8") +
"title=" + URLEncoder.encode(title, "UTF-8") +
"body" + URLEncoder.encode(jsonnode.toString(), "UTF-8") ;
httpcon.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
httpcon.connect();
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
Thanks.
You set the content length here:
httpcon.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
But the content you sent comes from here:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
So the reported Content-Length does not match the actual content length.
Ignore the httpcon.connect(); in the middle, it does nothing because you are already connected.
Instead, you need to do:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length()));
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

Categories

Resources