Passing data between android and server using JSON parsing - java

I'm trying to send and receive data between android app and server using JSON but unfortunately i am unable to do it i searched a lot but it didn't help. My code is as follows:
In android
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("fromDate", from);
jsonObject.put("toDate", to);
jsonObject.put("reason", reas);
new SendData().execute(jsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and then my asynctask's doInBackground method
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
CmsInter.TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CmsInter.TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(getResources().getString(
R.string.URL));
StringEntity se = new StringEntity(object.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
message = Sync.convertResponseToString(response);
} catch (Exception e) {
e.printStackTrace();
message = e.toString();
}
and then on server side within the doPost() method of servlet code is as follows :
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) { /* report an error */
e.printStackTrace();
}
String str = sb.toString();
try {
org.json.JSONObject json = new org.json.JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and I think this is not the right way to read JSONObject on the server side because when I run this I get org.json.JSONException: A JSONObject text must begin with '{' at character 1 exception , Can anyone please help me out in this. Any help will be appreciated. Thanks.

Finally got it this line was wrong object.toString() while sending it should have been object[0].toString() because asynctask's doInBackground methods parameter is an array i.e. protected String doInBackground(JSONObject... object).

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.

Reading large response body as HttpClient

I'm building an android application where I have to read a big chunk of information from a server.
The server sends the information as a JSONArray and everything is fine on the server side.
However the problem comes when I'm trying to receive this JSONArray as it seems to be too large for me to receive?
I connect to the server using HttpClient like this:
HttpParams httpParams = new BasicHttpParams();
int timeoutConnection = 20000;
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
int timeoutSocket = 20000;
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet request = new HttpGet();
request.setURI(url);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
if (response != null) {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 100000);
}
return in;
And I simply try to read what's in the BufferedReader with the readLine() method, however what I get back is not the full content of the response. I know this because I tried accessing the same content with a web browser and it returns the full content.
The response from the server is on a single line (might affect it, I don't know)
I'm able to read 4kb and I need to read a whopping 141kb (so I'm far off)..
My personal guess is that somewhere in my code there is a size limit.
Extra I read from the BufferedReader like this:
BufferedReader in = getResponse(new URI(params[0]));
// Read from the received buffer
String s;
StringBuilder sb = new StringBuilder(10000);
if(in != null){
while ((s = in.readLine()) != null){
sb.append(s);
}
}
Log.d("Problem: ", sb.toString());
EDIT: The response does not differ, it's always the same length
EDIT2: It seems that it was Log.d() that had a limit in print length! There was no problem to begin with... sorry!
Use Gzipped JSON in HTTP Request
Checkout this article: http://arnab.ch/blog/2012/09/android-how-to-send-gzipped-json-in-http-request/
Instead of reading the InputStream just directly convert it to String using EntityUtils.toString
example:
try {
response = client.execute(request);
HttpEntity resEntityGet = responseGet.getEntity();
final String result = EntityUtils.toString(resEntityGet); //result is your json response
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

android.os.networkonmainthreadexception error in my request response class for JSON

How should I use my aux class for JSON request, bcoz in android 2,3 work but android 4.x dont work
I read that I need to use Asyntask for fix it, or create thread, I prefer Asyntask but I cant compile it.
How fix my code for asyntask ?
public class Httppostaux {
InputStream is = null;
String result = "";
public JSONArray getserverdata(ArrayList<NameValuePair> parameters, String urlwebserver ){
//conecta via http y envia un post.
httppostconnect(parameters,urlwebserver);
if (is!=null){//si obtuvo una respuesta
getpostresponse();
return getjsonarray();
}else{
return null;
}
}
//peticion HTTP
private void httppostconnect(ArrayList<NameValuePair> parametros, String urlwebserver){
//
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlwebserver);
httppost.setEntity(new UrlEncodedFormEntity(parametros));
//ejecuto peticion enviando datos por POST
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error en la conexión HTTP "+e.toString());
}
}
public void getpostresponse(){
//Convierte respuesta a String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("getpostresponse"," result= "+sb.toString());
}catch(Exception e){
Log.e("log_tag", "Error conviertiendo el resultado "+e.toString());
}
}
public JSONArray getjsonarray(){
//parse json data
try{
JSONArray jArray = new JSONArray(result);
return jArray;
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
return null;
}}}
You should not perform network operations on main thread 4.0 and above. Read this to know how to perform network operations correctly https://developer.android.com/training/basics/network-ops/connecting.html
Here i put the sample code for how i use Asyc task for api calling, hope it will help for you and modify this code as per your need,
new Read().execute(); // Asyc Task initialization
public class Read extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(); // url executed here and the final value is stored in json obj
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Here you call the json obj and do your UI binding.
}
}
public JSONObject lastTweet() throws ClientProtocolException, IOException,
JSONException {
HttpClient client = new DefaultHttpClient();
StringBuilder url = new StringBuilder(<your_URL>);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
Log.e("RESPONSE VALUE IS", data); // Here you get the response
JSONObject last = new JSONObject(data);
return last; //here the response value is returned
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
In your manifest.xml don't forget to add this permission <uses-permission android:name="android.permission.INTERNET" />

Android: Uploading Strings To Server

I'm trying to let my users be able to report small errors my android application automatically catches to my server. It's nothing big, just a small text box and send button.
It's supposed to send 3 strings (error, optional user description, and time) to a file on my website made specifically to capture those errors. The thing is, I have absolutely no idea how to do so. I only know how to let my application read info from my website but not the other way around.
Do I have to have a special script on my website? Are JSON Strings necessary? I need the string to be saved there. (Not temporarily)
I'm a bit of a newbie so any help is appreciated. Thanks!
- There has to be a script running on your server, eg: php script.
- Its actually a web-service published on the server so that a client can access it.
- Then you will need to do a HTTP Post to the Server, its better to use NameValuePair along with it to send the data.
This is my code for doing HTTP POST:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now", sb + "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method " + sb.toString());
return sb.toString();
}
//////////////////////////// Edited Part ///////////////////////////////////
Server side php code:
<?php
require_once(ROOT.'/lab/lib/xyz_api_int.php');
try {
//setup the sdk
$api = YumzingApiInt::_get(
Config::get('api_int','url'),
Config::get('api_int','key'),
Config::get('api_int','secret')
);
//connect to the api
$api->connect();
//check our token
echo $api->getToken();
} catch(Exception $e){
sysError($e->getMessage());
}
You just need to post values by http to a php script on your server that will save those values in your file or a database.

Not getting JSON value in Spring Controller method

I need to send some data from my Android device to my server. I am doing this through JSON. I have implemented the JSON post on Android, and I am trying to do a mapping on the server side in order to retrieve that data. My problem is that I keep getting an empty string.
Android method used to send JSON:
private void sendJson(final String json, final String URL) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
try{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
client.execute(post);
}
catch(Exception e){
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Server-side method:
#RequestMapping(value = "/getLatestCalls", method = RequestMethod.POST)
public void getData(#ModelAttribute String json){
//... do something
}
The thing is that in this method my json String is "" every time. I have also tried using #RequestParam but with that it doesn't enter the method anymore. I have also tried with #ModelAttribute("json").
Can someone enlighten me a little here? Thank you in advance.
Here is the solution and it works fine.
server-side
#Controller
public class DataCollector {
#RequestMapping(value = "/clientdatacollector", method = RequestMethod.POST)
public #ResponseBody
void abc(Writer writer, #RequestParam("gpsdata") String gpsJSON) {
try {
// here is your jsonstring ;)
writer.write(gpsJSON.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client-side
public static void httptest() {
ArrayList<TravellingData> tdArray = new ArrayList<TravellingData>();
Gson gson = new Gson();
String jsonString = "";
for (int i = 0; i < 1; i++) {
tdArray.add(ObjectCreater.createMockTravellingDataObject());
}
jsonString = gson.toJson(tdArray);
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
try {
post = new HttpPost(
"http://localhost:8080/uygulama/clientdatacollector");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("gpsdata", jsonString));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = null;
try {
response = client.execute(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try using #RequestBody. It should work.

Categories