Sending JSON From Android to PHP - android

I've been struggling a bit on sending JSON objects from an application on android to a php file (hosted locally). The php bit is irrelevant to my issue as wireshark isn't recording any activity from my application (emulation in eclipse/ADK) and it's almost certainly to do with my method of sending:
try {
JSONObject json = new JSONObject();
json.put("id", "5");
json.put("time", "3:00");
json.put("date", "03.04.12");
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://localhost/datarecieve.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
I've modified this from an example I found, so I'm sure I've taken some perfectly good code and mangled it. I understand the requirement for multi-threading so my application doesn't hang and die, but am unsure about the implementation of it. Would using Asynctask fix this issue, or have I missed something else important?
Thankyou for any help you can provide.

Assuming that you are using emulator to test the code, localhost refers to the emulated environment. If you need to access the php hosted on your computer, you need to use the IP 10.0.2.2 or the LAN IP such as 192.168.1.3. Check Referring to localhost from the emulated environment
You can refer to Keeping Your App Responsive to learn about running your long running operations in an AsyncTask

you should use asynctask or thread, because in higher versions of android it doesn't allow long running task like network operations from ui thread.
here is the link for more description

Related

I cannot seem to find out if this webservice is getting the JSON object sent from Android

I have a android application which sends JSON information to a webservice for it to validate the information. I am using Kate as an editor for the webservice. The concept of JSON and php webservices is new to me. I normally code in java.
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
Log.i("username", jsonObject.toString());
jsonObject.put("password", password);
Log.i("password", jsonObject.toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return userID;
}
I found the StringEntity code online and thought it will work. I do not understand the purpose of the StringEntity for the HttpPost.
This is my webservice written in php.
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_POST['myusername'];
$password=$_POST['mypassword'];
//protecting mysql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
#$array = array($username,$password);
$sql = "SELECT first_name FROM $tablename WHERE u_username='$username' AND u_password=MD5('$password')";
//Querying the database
$result=mysql_query($sql);
if(!$result){
die(mysql_error();
}
//If found, number of rows must be 1
if((mysql_num_rows($result))==1){
//creating session
session_register("$username");
session_register("$password");
print true;
}else{
print false;
}
mysql_close();
I am not quite sure if the 'username' and the 'password' is being sent correctly from the android app to the webservice. How can I verify this? And is the webservice and the java code well-written to send the information in JSON?
When I go the webservice on the browser, I get the following error:
Parse error: parse error in E:\wamp\www\mobile.dcl.mu\webserver\login.php on line 24
Thank you in advance.
You try to bite off too much. It should be, like, 6 different questions (or just pay someone to write the scripts for you, or spend some time learning the technologies in isolation). Two first things to fix:
fix the parse error! it is as if you had a Java source that does not compile. The error is that you forgot the closing paren after die (mysql_error();
no, it will not work anyway. You send the data in the body as application/json, and you try to read it as url-encoded form. Decide which you want, ask for help on that.
remove the stripslashes. It does not add any security and will cause errors if anyone is using a slash in her password. Unless you have magic_quotes on, which you should not.
Since you made the three very basic mistakes so early, I am practically sure that there is much, much more to fix. Other than rewriting the whole thing for you or sending some general links on PHP programming and web application programming - I see no more way to help you. If you manage to split the problem, test things in isolation and ask more questions, there might be hope.
UPDATE
If you decide to standardize around JSON, the general pattern in your PHP files will be:
// get the body of the HTTP request (that's the "http entity")
$body = file_get_contents('php://input');
// translate JSON into ordinary PHP array:
$entity = json_decode($test, true);
// Now you can read parts of it as if you read an array;
// the data may be nested and will mirror exactly your JSONObject:
$username=$entity['myusername'];
$password=$entity['mypassword'];
[yes, that's me begging for an upvote :-)]
[and I think there is more problems in your Java code, but one thing at a time]

Http Post Request in Android won't return appropriate data?

Okay, so I was trying to send Http Post Requests to this one site, and I sniffed the sent request with wireshark thus getting the text data from the post request of this site. I used this in a stock Java application, and it worked perfectly fine. I could use the post method regularly with no problem whatsoever, and it would return the appropriate website. Then I tried doing this with Android. Instead of returning the actual html data after executing the post request, it returns the regular page html data untouched. It DOES send a post request (sniff with wireshark again), it just doesn't seem to get the appropriate response. I took the exact same method used from another one of my projects, which worked perfectly fine in that project, and pasted it into my new project. I added the INTERNET user permission in Android, so there's nothing wrong with that. The only visible difference is that I used NameValuePairs in the other one (the one that worked) and in this one I'm directly putting the string into a StringEntity without encoding (using UTF-8 encoding screws up the String though). I used this exact same line of text in regular Java like I said, and it worked fine with no encoding. So what could be the problem? This is the code:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
post.setEntity(new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
Can you see what's wrong here?

"SSLPeerUnverifiedException: no peer certificate" android backend

so this is for a project im doing for my school in which we need a backend.
our current setup is that the foreground is an android app, whereas the backend is a mySQL database that is located within my school's servers. The android app is supposed to interact with the mySQL database using a php script.
my php script is set currently hardcoded to return one single row from the mySQL database in JSON format.
my android code is as follows:
public static final String KEY = "URL of my PHP script";
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(KEY));
Log.d(null,"there");
HttpResponse response = httpclient.execute(request);
Log.d(null, "here");
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
However, I get an exception at the line
HttpResponse response = httpclient.execute(request);
in which the error says: No Peer Certificate.
Anyone know what's wrong with it, and how to fix it?
I have the same issue. This link worked for part of my needs.
http://www.knowledgebit.appspot.com/zahangirbd/TopicView.action;jsessionid=E2BZt_6bp4uFFbMyq42gWg?id=56001
however, there is still an issue with some links(i believe im not providing the proper certificate)
EDIT: so it turns out that the order of the certificates were the problem.
check this out, this helped me..
Apache HttpClient on Android producing CertPathValidatorException (IssuerName != SubjectName)

Android Send data back to server

How would one go about sending data back to server, from an android application?
I've already tried using HttpPost and posted back to a RESTful WCF service, but I couldnt get that to work (I've already created a SO question about this, without finding the solution..) - No matter what I do I keep getting 405 Method not allowed or the 400 Bad Request.. :(
I'm not asking for full code example necessarily.. just a pointer in a direction, which can enable me to send data back to a server.
It is important that the user should not have to allow or dismiss the transfer.. it should happen under the covers, so to speak
Thanks in advance
Services is the way to go. REST (I recommend this one on Android), or SOAP based. There're loads of tutorials on getting an android app communicate a service, even with .net / wcf ones.
Tho you can always just open raw sockets and send data with some custom protocol.
Edit:
Here's the doInBackground part of my asynctask handling http post communication, maybe that'll help:
protected String doInBackground(String... req) {
Log.d(TAG, "Message to send: "+req[0]);
HttpPost p = new HttpPost(url);
try{
p.setEntity(new StringEntity(req[0], "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
try{
HttpResponse resp = hc.execute(p, localContext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
Log.d("Response", "Response is " + response);
} catch (Exception e){
e.printStackTrace();
}
return response;
}

How to improve my Rest Calls on Android?

I am making an app for Android. I like to make the rest calls as quick as possible. When I get my results as XML it takes 5 seconds (!) to get a simple xml like this:
<souvenirs>
<souvenir>
<id>1</id>
<name>Example 1</name>
<rating>3.4</rating>
<photourl>/images/example.jpg</photourl>
<price>3.50</price>
</souvenir>
<souvenir>
<id>2</id>
<name>Example 2</name>
<rating>2.4</rating>
<photourl>/images/example.jpg</photourl>
<price>8.50</price>
</souvenir>
</souvenirs>
So I tried it with JSON. But that takes also about 5 seconds to retrieve.
I load the XML in android with the following code:
URL url = new URL("http://example.nu?method=getAllSouvenirs");
URLConnection conn = url.openConnection();
long t=System.currentTimeMillis();
InputStream ins = conn.getInputStream();
Log.d("info", String.valueOf((System.currentTimeMillis()-t)));
The log says it takes about 5000 ms to get the inputstream.. Is there any way to speed this up? does anybody knows which technique the Android Market uses? This loads way faster than my app..
Thanks in advance! :)
When you try to get the data "manually" - via browser or via other means (wget, curl) how long does it take there.
On Android you also should take the mobile network into consideration that is usually significantly slower than for a desktop computer. Also latencies are bigger.
To me this sounds a lot like issues in the backend (e.g. trying to resolve the IP of the client and thus taking lots of time).
use Apache HttpClient instead of URLConnection:
Apache http client or URLConnection
EDIT(2012-02-07): no longer true on newer android platform please read: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Maybe that is how it is implemented and you can't do nothing. That is my guess.
My opinion is to do all connection based stuff on your own thread (to put in in background) and in foreground (main UI thread) entertain user. :)
I have played a little bit around this and it works fast enough for me... Here is my code:
private static HttpResponse doPost(String url, JSONStringer json) {
try {
HttpPost request = new HttpPost(url);
StringEntity entity;
entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
request.setEntity(entity);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
return response;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
And somewhere else I call that method like:
HttpResponse httpResponse = doPost(url, json);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
It works fine for me...

Categories

Resources