I have developed an application which uses GCM notifications, i have successfully registered the device with GCM, and retrieved regId, now i want to send this ID to my server.
i am using this code to send the regId:
package com.example.gcm;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.util.Log;
public class ShareExternalServer {
public String shareRegIdWithAppServer(final Context context,
final String regId) {
String result = "";
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("regId", regId);
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry<String, String>> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post new one1 Failure." + " Status: " + regId;
}
} finally {
if (httpCon != null) {
httpCon.disconnect();
}
}
} catch (IOException e) {
result = "Post Failure 33 . Error in sharing with App Server."+regId;
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}
Related
I have the following function to allow my android app to communicate with a web server. However the app shows a 'Please Wait' message when I call this code and only disappears if a new activity loads in or if I press the back button. Where is the Please wait coming from and how can I avoid it appearing? Thanks
package util.sapa.sapacontainermanager5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class SimpleWebCalls {
public String executeHttpGet(String serverIP, String nvp) {
String lines="";
serverIP="???????????";
URL url = null;
try {
url = new URL("http://" + serverIP + "/WCF.aspx?" + nvp);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("GET");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
lines+=line;
}
in.close();
return lines;
} catch (IOException e) {
e.printStackTrace();
}
} catch (ProtocolException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
}
the above class is called from:
public String GetDataFromServer(String serverIP,String nvp) {
SimpleWebCalls tWebCall = new SimpleWebCalls();
String sReturn="";
sReturn= tWebCall.executeHttpGet(serverIP,nvp);
return sReturn;
}
the above function is called from:
String data="";
data="doAction=location&u=" + sess.getUserName()+
"&p=" + sess.getPwd() +
"&uid=" + sess.getUserID() +
"&lf=" + sess.encodeStr(editScannedCode.getText().toString());
result = sess.GetDataFromServer(serverIP,data);
follow this tutorial link it might be helpful to you.
add GetDataFromServer() method in to your doInBackground() method.
I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);
I want to do an App. It can realize to upload the phone picture to server. Now it can take the picture and save to the mobile phone. But it can not upload into server. How to deal with this? The server is using tomcat to setup.
Android upload code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class uploadActivity extends Activity
{
private Button uploadbutton;
private String uploadFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String actionUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
uploadbutton=(Button)findViewById(R.id.button2);
uploadbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
private void uploadFile()
{ String uploadUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();//
dos.close();
is.close();
} catch (Exception e)
{
e.printStackTrace();
setTitle(e.getMessage());
}
}
}
The server code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CameraServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out2 = response.getWriter();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String uploadPath = "d:\\cameraupload\\";
File file = new File(uploadPath);
if (!file.exists())
{
file.mkdir();
}
String filename = "";
InputStream is = null;
for (FileItem item : items)
{
if (item.isFormField())
{
if (item.getFieldName().equals("filename"))
{
if (!item.getString().equals(""))
filename = item.getString("UTF-8");
}
}
else if (item.getName() != null && !item.getName().equals(""))
{
filename = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
is = item.getInputStream(); // 得到上传文件的InputStream对象
}
}
filename = uploadPath + filename;
if (new File(filename).exists())
{
new File(filename).delete();
}
// Began to upload files
if (!filename.equals(""))
{
// use FileOutputStream to open the upload file in server
FileOutputStream fos2 = new FileOutputStream(filename);
byte[] buffer = new byte[8192];
int count = 0;
// Began to read the upload file in bytes,and input it to server's upload file output stream
while ((count = is.read(buffer)) > 0)
{
fos2.write(buffer, 0, count); // To write the byte stream server files
}
fos2.close(); // close FileOutputStream object
is.close(); // InputStream object
out2.println("file upload success!xii");
}
}
catch (Exception e)
{
}
}
}
Do you have any error tracing?? Our just happening nothing??
For using httpurlconnection, you need to change the policy at the beginning:
ThreadPolicy mThreadPolicy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mThreadPolicy);
Try this.
Isn't 192.168.1.105 an IP-adress on the local network? Are you sure it's reachable from your phone? Open your phone's browser and try to navigate to the URL, can you reach it?
At what end are you having problems with the upload? Client or server? If it's on the client, what error are you getting? Or is it silently failing? Have you tried to make a simple HTML form and do the upload from there? If that is working you know it's your Android code that is the problem?
Also, it hurts every time I see someone trying to implement file uploads on their own. I'm not saying that your code is wrong, but it's an awful lot of lines of code (thus more risk of errors) compared to if you'd use a 3rd party library to abstract away all of that code for you. A well known and popular library such as Android Asynchronous Http Client has good support for file uploads out of the box:
AsyncHttpClient client = new AsyncHttpClient();
String filename = "file.png";
File myFile = new File("/path/to/" + filename);
RequestParams params = new RequestParams();
try {
params.put("file", myFile);
params.put("filename", filename);
client.post("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet", params, responseHandler);
}
catch(FileNotFoundException e) {
// handle
}
Try this...add apache-mime4j-0.6.jar and httpmime-4.0.3.jar libs
File f=new File(exsistingFileName);
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet");
MultipartEntity Mentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String url1=exsistingFileName;
String mime;
String extension = MimeTypeMap.getFileExtensionFromUrl(url1);
if (extension != ""&&extension!=null) {
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(extension);
}
else
{
String ext = url1.substring((url1.lastIndexOf(".") + 1), url1.length());
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(ext);
}
ContentBody cbFile;
if(mime!=null)
cbFile= new FileBody(f,mime);
else
cbFile=new FileBody(f);
Mentity.addPart("file",cbFile);
post.setEntity(Mentity);
HttpResponse response = null;
try {
response = http.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
responseString = new BasicResponseHandler().
handleResponse(response);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
I am fairly new to Android development, and am making a program to translate things using the Google translate API. The error is as follows: 'Syntax error on token(s), misplaced construct(s). Thank you. Here is my Java file:
package org.example.translate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.BufferedReader;
public class TranslateTask implements Runnable {
private static final String TAG = "TranslateTask";
private final Translate translate;
private final String original, from, to;
TranslateTask(Translate translate, String original, String from, String to) {
this.translate = translate;
this.original = original;
this.from = from;
this.to = to;
}
public void run() {
String trans = doTranslate(original, from, to);
translate.setTranslated(trans);
String retrans = doTranslate(trans, from, to);
translate.setRetranslated(retrans);
}
private String doTranslate (String original, String from, String to) {
String result = translate.getResources().getString(
R.string.translation_error);
HttpURLConnection con = null;
Log.d(TAG, "dotranslate(" + original + ", " + from + ", " + to + ")");
//*This is where the error occours*// try {
if (Thread.interrupted())
throw new InterruptedException();
// Build RESTful query for Google API
String q = URLEncoder.encode(original, "utf-8");
URL url = new URL(
"http://ajax.googleapis.com/ajax/services/language/translate"
+ "?v=1.0" + "&q=" + q + "&langpair=" + from
+ "%7C" + to);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.addRequestProperty("referer",
"http://www.pragprog.com/titles/eband3/hello-android");
con.setDoInput(true);
con.connect();
if (Thread.interrupted())
throw new InterruptedException();
BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String payload = reader.readLine();
reader.close();
JSONObject jsonObject = new JSONObject(payload);
result = jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("'", "'")
.replace("&", "&");
if (Thread.interrupted())finally
throw new InterruptedException();
} catch ("IOException", e) {
Log.e(TAG, "IOException" e);
}
catch ("JSONException", e) {
Log.e(TAG, "JSONException", e);
}
catch (InterruptedEception e) {
Log.d(TAG, "InterruptedException", e);
result = translate.getResources().getString(
R.string.translation_interrupted);
}
finally {
if (con!= null) {
con.disconnect();
}
};
};
}
Please help me! Clear answers are appreciated
The only thing that I can see (and it might have been a mistake from copy/pasting) is that you have a random finally floating on one of your lines:
JSONObject jsonObject = new JSONObject(payload);
result = jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("'", "'")
.replace("&", "&");
if (Thread.interrupted())finally // <-- this doesn't belong :)
throw new InterruptedException();
} catch ("IOException", e) {
Log.e(TAG, "IOException" e);
}
I had already been able to
get the server authrization and saving it to datastore;
registering the phone to c2dm server and;
sending the id to the app server which save the application c2dm regeistration id to datastore.
Now I just want to implement a servlet that retrieves the server token no. and android application regirstration id from datastore and use them to push a message to phone.
This is the code for the servlet:
package com.visd.myfirstapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
//import com.visd.myfirstapp.MessageUtil.CustomizedHostnameVerifier;
public class Visd extends HttpServlet {
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
resp.setContentType("text/plain");
Entity appRegIdEntity = null;
Entity serverTokenEntity = null;
int RetCode = 0;
String message = "Congrats C2DM process completed";
Key appRegIdKEY = KeyFactory.createKey("c2dmreg","cr");
Key serverTokenKEY = KeyFactory.createKey("vToken", "tokenkn");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String appRegId = null, serverToken = null, chk =null;
try {
appRegIdEntity = datastore.get(appRegIdKEY);
serverTokenEntity = datastore.get(serverTokenKEY);
serverToken = (String) serverTokenEntity.getProperty("token");
appRegId = (String) appRegIdEntity.getProperty("c2dmid");
RetCode = sendMessage(serverToken, appRegId, message);
} catch (EntityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
chk = "Entered In Exception";
}
resp.getWriter().println("Return code :" + RetCode + "chk value :" + chk);
}
// Message Sending method
public static int sendMessage(String auth_token, String registrationId, String message) throws IOException
{
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0");
postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
URL url = new URL("https://android.clients.google.com/c2dm/send");
//HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());//commented as was causing error, i dont know why
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
return responseCode;
}
}
But the browser always shows the RetCode = 0 and Chk value = "Entered in Exception" i.e.It never sends the message to the android device, instead always enters in the exception. What wrong in the code i couldn't figure out..
please help.
Thank you.
This is how I finally solved, code help :-
public class C2dmsender {
public static String send(String regid, String appRegId, String mtype, String[] message) throws UnsupportedEncodingException
{
String serverToken = ""//give the sever token here;
data.append("registration_id=" + appRegId);//appRegId is the C2DM id of the device in which you want to push
// Collapse key is for grouping messages and only the last sent message
// with the same key going to be sent to the phone when the phone is
// ready to get the message if its not from the beginning
data.append("&collapse_key=test");
// Here is the message we sending, key1 can be changed to what you whant
// or if you whant to send more then one you can do (i think, not tested
// yet), Testing is the message here.
data.append("&data.key1=");
// If you whant the message to wait to the phone is not idle then set
// this parameter
// data.append("&delay_while_idle=1");
byte[] postData = data.toString().getBytes("UTF-8");
try {
// Send data
URL url = new URL("https://android.apis.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ serverToken);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
Integer responseCode = conn.getResponseCode();
if (responseCode.equals(503)) {
// the server is temporarily unavailable
} else {
if (responseCode.equals(401)) {
// AUTH_TOKEN used to validate the sender is invalid
} else {
if (responseCode.equals(200)) {
// Check for updated token header
String updatedAuthToken = conn
.getHeaderField("Update-Client-Auth");
if (updatedAuthToken != null) {
serverToken = updatedAuthToken;
}
String responseLine = new BufferedReader(
new InputStreamReader(conn.getInputStream()))
.readLine();
}
}
} catch (Exception e) {
}
}
}