I have an android app and am trying to send data to the PHP on the server. The server gets the php data with
$this->get('uname');
$this->get('pass');
We do use codeigniter if that matters
The Java code, inside of an Async method, I currently have is
InputStream response = null;
URLConnection connection = new URL(urls[0]).openConnection();
connection.setRequestProperty("uname" , Username);
connection.setRequestProperty("pass", Password);
response = connection.getInputStream();
When I run this, the code always returns null but it is supposed to return a JSON array either way. I have checked the URL and it is correct. What am I doing wrong? Thanks!
You code should be like this
For your android side ,as mentioned by #Ichigo Kurosaki at Sending POST data in Android
For Codeigniter side , cosider you function name is user_login
function user_login(){
$uname = $this->input->get_post('uname'); //get_post will work for both type of GET/POST request
$pass = $this->input->get_post('pass');
$result=$this->authenticate->actLogin($uname,$pass ); //considering your authenticating user and returning 1,0 array as success/failure
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
exit;
}
Related
I have table called GRN and in that so many columns are there with lots of data.
Now i want to sync that GRN data with the server's database.
So we can say whatever data we have in android app for GRN that i need to insert in server's database during sync.
I know how to pass 1 record in post but i want to pass all the data in post during web service calling from Android app.
How to post data to a webservice using json
In this link we can see how to pass some parameter in post.
Does anybody know?
Try putting all the data in a Json string (use a library, like org.json). Then you will need to parse it on the server side.
With org.json, you will simply do something like this:
JSONObject o = new JSONObject();
o.put("key1", "value1");
o.put("key2", "value2");
String dataToSend = o.toString();
To make it an array, do something like this:
JSONArray a = new JSONArray();
for([Some loop]){
JSONObject o = new JSONObject();
o.put("key", "value");
a.put(o);
}
String dataToSend = a.toString();
I have the following web method in my web api controller
public HttpResponseMessage PostMakeBooking(FacilityBookingRequest bookingRequest)
{
var returnStatus = HttpStatusCode.OK;
var json = new JavaScriptSerializer().Serialize(bookingRequest);
var response = Request.CreateResponse<CardholderResponse>(returnStatus, cardholderResponse);
return response;
}
When I make this call from my .NET app, my json string appears correctly when I seralize it
{"correlationId":null,"RequestId":"7ec5092a-342a-4e32-9311-10e7df3e3683","BookingId":"BK-123102","CardholderId":"123456","BookingFrom":"\/Date(1370512706448)\/","BookingUntil":"\/Date(1370523506449)\/","DeviceId":"ACU-01-R2","Action":"Add","LoginId":"tester","Password":"tester"}
However, when I made to call from my php script
public function web_request(){
$guid =self::getGUID();
$replace = array("{","}");
$guid = str_replace($replace, "", $guid);
$client = new Zend_Rest_Client("http://203.92.72.221");
$request= new myZendCommon_FacilityBookingRequest();
$request->RequestId =$guid;
$request->BookingFrom ="27/03/2013 05:30";
$request->BookingUntil ="27/03/2013 06:30";
$request->CardholderId ="E0185963";
$request->DeviceId ="ACU-B2-01-R1";
$request->BookingId ="111";
$request->Action ="Add";
$request->LoginId ="tester";
$request->correlationId ="(null)";
$request->Password ="tester";
$request = json_encode($request);
$response = $client->restPost("/ibsswebapi/api/facilitybooking",$request);
print_r($response);
exit();
The call goes to my web method, but when I serialize it using JavaScriptSerializer().Serialize(bookingRequest)
{"correlationId":null,"RequestId":null,"BookingId":null,"CardholderId":null,"BookingFrom":"\/Date(-62135596800000)\/","BookingUntil":"\/Date(-62135596800000)\/","DeviceId":null,"Action":null,"LoginId":null,"Password":null}
All the values are null.
Is something wrong with the script?
I believe Kiran is right. Not sure why some one has felt his answer is not useful. Anyways, my understanding is that you are creating a JSON string and doing a form post of the same. I guess in this case the content type is sent as application/www-form-urlencoded but request body is a JSON string. You can use Fiddler to see how the request is being sent by the PHP script. I don't have the PHP knowledge to tell you how you can post JSON but my guess is that if you just remove the JSON encoding line $request = json_encode($request);, it should be okay.
From ASP.NET Web API point of view, if the request has Content-Type: application/json header and the body has the right JSON or if the request has Content-Type:application/www-form-urlencoded header and the body has the form url encoded content like RequestId=7ec5092a-342a-4e32-9311-10e7df3e3683&BookingId=BK-123102 and so on, web API will absolutely have no problem in binding. Currently, the request is not being sent in the right format for web API to bind.
Are you sending the header Content-Type:application/json in your request?
Also add the following piece of code to catch any model state validation errors:
.
if (!ModelState.IsValid)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}
I have an algorithm about chat program in android, but I have a problem in server-side section.
I can store my data like username, password and e-mail through json into my database from my app but I do not know that How can I check them into my app! (e.g Get the response of username checking query into my app.)
Thanks in advance.
Basically when you run httpClient.execute it will return a response, you need to use that response.
Client side:
HttpResponse resp = httpClient.execute( post );
DataInputStream is = new DataInputStream( resp.getEntity().getContent() );
Server side depends on what programming language you use. For example using python:
self.response.headers['Content-Type'] = 'text/vnd.aexp.json.resp'
self.response.set_status( 200,"OK" )
self.response.out.write( json.dumps( responseList ) )
See this example for full source code and details:
http://mylifewithandroid.blogspot.fi/2010/10/client-server-communication-with-json.html
EDIT
Check this for php server side:
http://www.happycode.info/php-json-response/
I'm going nuts! Maybe someone can help me?!
I have an sqlite-database on a running server, which I receive due to an php-script. (To make it clear: I'm calling an php-script which gives me the the database as a response). With the response I'm now trying to "parse" it to an regular *.db file which I later on use for my app.
the app works fine, while placing the *.db into the assets folder. But I need to get the updated database everytime when calling the app. Therefore I need to receive it somehow from the server.
Just for notice: I don't know why they use a php-script for that, but it works perfectly with the iOS-Version of the app. So I am 100% sure that the script does work.
Got any hints or a solution to that?
Thanks!
EDIT: here is what I'm trying to do.
private void copyDatabase() {
InputStream myInputDB = null;
OutputStream myOutputDB = null;
HttpResponse response = null;
// Path to the just created empty db
String dbFilePath = DB_PATH + KeyConstants.DB_NAME;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://USERNAME:PASSWORD#ADRESS/u/db.php");
try {
response = httpClient.execute(httpPost);
//Open your local db as the input stream
myInputDB = response.getEntity().getContent();
//Open the empty db as the output stream
myOutputDB = new FileOutputStream(dbFilePath);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInputDB.read(buffer)) > 0){
myOutputDB.write(buffer, 0, length);
}
//Close the streams
myOutputDB.flush();
myOutputDB.close();
myInputDB.close();
} catch (IOException ioEXC) {
throw new Error("Problem copying database from resource file.");
}
What do You have the problem with? With the Android app or with the PHP script?
I don't understand why there is a whole DB file request-response and not just the data (and better in some lazy reading), but that's not matter of Your case.
If You need to "download" all the DB at every run You should call and implement some method to do so - in the very first Activity call this method within onCreate() method. You can create a simple method within this Activity or in better approach create a simple class for this that will be instanciated and its method called within the first activity's onCreate().
But maybe I just don't understand You question...
EDIT: try reading through this problem: Can I download an SQLite db on /sdcard and access it from my Android app?
I am currently developing Android application, which will uses web services. I used PHP for backend. I am currently trying authentication via JSON to PHP. But I am stuck at some point, hope u guys will help.
I successfully write code to create JSON data in android also db connections in php using mysql, but i am confusing about how to handle JSON data. I am using POST request for sending JSON data.
I like to ask how i handle JSON data in PHP. More specific, I like to know how to grab POST request in PHP which contain JSON data??
Thanks in advance.
Thanking you.
EDIT:
I am using following code for sending POST request in android
HttpPost post = new HttpPost(address);
json.put("username", username);
json.put("password", pwd);
StringEntity se = new StringEntity("json"+json.toString());
Log.i(DEB_TAG, "The JSON Request is:"+json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
Log.i(DEB_TAG, "The post request is "+post.toString());
response = client.execute(post);
if(response != null){
InputStream in = response.getEntity().getContent();
Log.i(DEB_TAG, "The result is"+in.toString());
}
and using following code for parsing JSON request in php:
$string = $_POST['josnHeader'];
$obj = json_decode($string);
$username = $obj->{'username'};
$password = $obj->{'password'};
Is it correct or I am doing any wrong implementation??
Have you taken a look in your $_POST array in PHP?
$json = $_POST["var_name"];
$array = json_decode($json);
$json = $_REQUEST["your_param"];
$dtoObject = json_decode(stripslashes($json),true);