Android/PHP: how to POST/GET JSON data from Android to php

Android/PHP: how to POST/GET JSON data from Android to php?

Currently I am stuck at a point where I am sending JSONObject data to php but getting NULL values always in response.

What I want:

I am sending 'username' and 'password' from Android in the form of JSONObject and want to retrieve same data in JSONObject in PHP response.

Here is my code snippet

Android_file.java

DefaultHttpClient httpClient=new DefaultHttpClient(); HttpPost httpPost=new HttpPost(register_user); JSONObject jsonObject=new JSONObject(); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); try { jsonObject.put("username",username.getText().toString()); jsonObject.put("password",password.getText().toString()); StringEntity se=new StringEntity("json="+jsonObject.toString()); //httpPost.addHeader("content-type", "application/x-www-form-urlencoded"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json")); httpPost.setEntity(se); String req=se.toString(); HttpResponse response=httpClient.execute(httpPost); if(response!=null){ InputStream is=response.getEntity().getContent(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is)); StringBuilder sb=new StringBuilder(); String line=null; while((line=bufferedReader.readLine())!=null){ sb.append(line+"\n"); } this.message=sb.toString(); //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Login_check.php

<?php include('../core/init.php'); // $contents = file_get_contents('php://input'); // $contents = utf8_encode($contents); if($_POST['json']) { $data=json_decode(stripslashes($_POST['json'])); $username=$data['username']; $password=$data['password']; $response=array('username'=>$username,'password'=>$password); echo json_encode($response); } else{ $no_data=array('none'=>'no data received'); echo json_encode($no_data); } ?>

Please let me know if I am doing something wrong or missing some point? thanks in advance!

-------------Problems Reply------------

I dont know what exactly is wrong with your code but I compared your code to mine which is working fine on diffrent apps and I made some changes to your code and hope that it works:

replace the part:

jsonObject.put("username",username.getText().toString());
jsonObject.put("password",password.getText().toString());
StringEntity se=new StringEntity("json="+jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPost.setEntity(se);

With:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username.getText().toString()));
params.add(new BasicNameValuePair("password",password.getText().toString()));
httpPost.setEntity(new UrlEncodedFormEntity(params));

and this will be your web service (I think the problem is here):

<?php
include('../core/init.php');

// $contents = file_get_contents('php://input');
// $contents = utf8_encode($contents);
if(isset($_POST['username']) && isset($_POST['password']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$response = array();
$response['username'] = $username;
$response['password'] = $password;
echo json_encode($response);
}
else{
$no_data=array();
$no_data['none']= 'no data received';
echo json_encode($no_data);
}
?>

Please let me know if it fixes your problem.

Category:php Views:4 Time:2018-06-11
Tags: php json android

Related post

  • How to post nested JSON data in Android? 2013-11-18

    I need to post the below JSON data from Android to a Webservice. This is JSON data {"AutoMobileName":"Mercedes","Engine":"V4","BrandInfo":{"Model":"C500","ColorType" : "Black","DatePurchased":"1990"}} Using Android Java i am doing like this.. JSONObj

  • How do I get JSON data from RESTful service using Python? 2011-10-13

    Is there any standard way of getting JSON data from RESTful service using Python? I need to use kerberos for authentication. some snippet would help. --------------Solutions------------- Something like this should work unless I'm missing the point: i

  • How do I get JSON data from a server into a javascript variable 2014-10-26

    Something so trivial and I just can't seem to find an answer. This is my code so far. However this is with the JSON alredy set as a variable. I need it so that it gets the JSON text from http://localhost:3001/sync/ and makes it equal to var txt. INST

  • Getting JSON data from URI with PHP without using cURL 2010-11-04

    So, I have a IIS machine with PHP and I need to grab the data from a URI that is returned in JSON format, ie: http://finance.google.com/finance/info?client=ig&q=NYSE:GOOG The trick is, I can't use cURL to do it. Is there a way to do this so that

  • How can i get json data from javascript file? 2011-12-06

    I have request $.ajax({ url: 'http://translate.google.ru/translate_a/t', data: { client: "x", text: sourceText, sl: langFrom, tl: langTo }, dataType: 'jsonp', success: function (data) { alert("Success"); } In response to this process i have file t.js

  • getting json data from php server with """ 2011-06-30

    My iphone app getting json data from php server. 2 basic questions, just to be sure : 1-In some of the json data fields, i see "&quot;", is this how json send Quotes, and I need to clean it in the iphone app ? or there is elegant and clean way to

  • How to get the data from android? 2011-12-02

    This question already has an answer here: In Android: How do I get variables/data from one screen to another? 4 answers I am storing the string values in arraylist in Select.java page. Now I need to get those string values into other page i.e review.

  • how can i get the data from dotnet web-services in android? 2012-01-20

    I am new to web-services. i have save my data in web-services but i doesn't know how to get that data from web-services. my web-services in .net in that web-services i have use SOAP parsing. so please help me how can i get the data from url.i have se

  • Send JSON data from Javascript to PHP? 2011-12-22

    How can I send JSON data from Javascript in the browser, to a server and have PHP parse it there? --------------Solutions------------- I've gotten lots of information here so I wanted to post a solution I discovered. The problem: Getting JSON data fr

  • Strange characters contain when I get JSON data from server in developing iOS App 2014-08-27

    I am developing iOS App. I get JSON data from PHP server in the following code. NSURL *requestUrl = [NSURL URLWithString:urlString]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:requestUrl]; NSHTTPURLResponse *httpResponse; NSData *data

  • Getting Json data from another domain, within a proxy servlet 2010-08-06

    I'm working on a GWT project, in which I have to fetch some JSON data from a real web-domain. Due to SOP policy, GWT fails to get those data. To address this, as suggested in GWT docs, I have created some proxy servlets within GWT, which in turn shou

  • How does one get row data from a Silverlight DataGrid? 2011-05-27

    In Silverlight, how does one get row data from a DataGrid that is full of data? I have gotten this far (in a method that receives a button click on a row(: DataGridRow item = (DataGridRow)dg.SelectedItem; Now, how do I get the individual components o

  • how do I get / transfer value from Javascript to PHP variable (it has checked "no" in radio button) in different page? 2012-02-14

    how do I get / transfer value from Javascript to PHP variable (it has checked "no" in radio button) in different page? For example my script on Javascript: <script language="Javascript"> function getReject(){ var RadioButton = document.getEleme

  • How do I get the data from datasets & I view on the DataGridView with a different layout formats 2011-05-02

    Can you help my problem? I have 2 tables : product (as parent) and sales (as a child). product table consists of: product_id | product_name | product_price | 1 | book | $5 | sales table consist of: transaction_id | product_id | quantity | total_price

  • How i can return jSon Data from jQuery Dialog to Parent form 2011-08-20

    can anybody say "how i can pass jSon Data from jQuery dialog form to Parent form?" I want to create a search window where user will select client name then selected client name and id will appear in parent form using ASP.net MVC 3. Thanks in advance.

  • My system is not working,I have send it to a computer shop, they claim the motherboard is faulty. Kindly advice how can I get my data from the hardisk. 2013-02-18

    My system is not working,I have send it to a computer shop, they claim the motherboard is faulty. Kindly advice how can I get my data from the hardisk. --------------Solutions------------- Hello ak9365 The compurer shop should be able to do that for

  • how to get json data from iphone post request 2010-09-07

    I am developing an iPhone App using JSON framework, I am calling a PHP script to update MySQL database on local server. Using these code: NSString *jsonString = [sendData JSONRepresentation]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc

  • How can I get Json data in PHP which pass through AJAX function 2014-02-27

    I have an AJAX function like below, which will send a Json data to PHP file, How can I get these data in PHP file ? $.ajax({ type: 'POST', url: 'data11.php', data: { json: ko.toJSON(viewModel) }, success: function () {} }); My Json data is something

  • how to get json data with curl and php from another domain? 2011-12-21

    i am triong to do a request to a page and get back some results using curl. with javascript i could use $.getJSON like so: $.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(respons

  • PHP: How do I get an attribute from a JSON array? 2010-07-08

    I have the following JSON array: <?php $json = { "status": "OK", "results": [ { "types": [ "street_address" ], "formatted_address": "5721 N Northcott Ave, Chicago, IL 60631, USA", "address_components": [ { "long_name": "5721", "short_name": "5721"

  • How can I get JSON data without an array as the key? 2012-02-05

    I'm trying to get JSON data to turn it into html but the JSON code I have access to does not show an array to use as the data key. Does anyone know how I can go about getting this data? My data values are coming up "undefined" in the HTML. Sample dat

  • Is it Possible to get itunes like xml/json data from android market for each App 2012-03-09

    Itunes provide URL or all apps in App-store like to get details in JSON/XML Format http://itunes.apple.com/lookup?id=[appid] There is no any API for android market i have got online. i tried to get details from these html pages using java script by f

  • How do I get JSON data in a plain c# program from a ASP.net MVC program? 2011-10-28

    I am a newbie in asp.net MVC. I want to create a plain c# client program that consumes json returned from a asp.net mvc progam. What is the best method for retrieving the json data from the asp.net MVC site? I currently use WebRequst, WebResponse and

  • How do you request JSON data from an API on a different domain? 2011-09-14

    I was trying to retrieve some JSON data from Google's AppEngine, and also a test domain I setup, and I can't figure out how to use jQuery to access this remote data. Works fine on the local server =/ var _this = this; $.getJSON(url,input,function(_da

  • JSON-data from iOS into PHP-script 2011-12-20

    How can I access json data within a php-script, which it received via http-post? I'm doing the following on the iOS-side: NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL]; NSMutableURLRequest *req = [NSMutableURLReq

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.240 (s). 11 q(s)