I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<Your URL to php file>);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
finalResult = st; // You should register a variable for finalResult;
} catch (Exception e) {
Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
}
return "OK";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After that, you will have final result and process to do with it here
// Below is my simple code, please change it
if(finalResult.equals("1")){
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
}
// End
}
Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
Note: Replace TK_Configuration.TAG << by your TAG.
you have commented this line it means you are not passing values from Android
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
remove comment from this line.
One more thing, you are passing username but from php you are trying to fetch value as $user = $_POST['name'];, both name must be same.
For some reason I can not get my async task to pass along the post params I set. Any help is appreciated.
Here is my onClick which calls the thread. Please note that customerInfo is not null, and each index has a value.
EDITED: moved client and post declaration into doInBackground and took out extra, unneeded thread.
EDITED2: Apparently when hitting a subdirectory on your web server, and you declare your url like
http://IP/subDirectory
without the trailing "/" apache doesn't pass the parameter to your index.php.
#Override
public void onClick(View v) {
new RegisterPost(progress).execute();
}
Here is my doInBackground
#Override
protected Void doInBackground(Void... voids) {
String[] customerInfo = getRegistrationInfo();
// Post
// Send info to tmiszone
String url = "http://SERVER_ADDRESS/"; // I had to add index.php to my url to get around the issue.
client = new DefaultHttpClient();
post = new HttpPost(url);
// Set post parameters
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("salesCode", customerInfo[0]));
pairs.add(new BasicNameValuePair("firstName", customerInfo[1]));
pairs.add(new BasicNameValuePair("lastName", customerInfo[2]));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Make connection
try {
response = client.execute(post);
} catch (ClientProtocolException e){
// TODO handle
response = null;
} catch (IOException e) {
// TODO handle
response = null;
} catch (Exception e) {
// TODO handle
response = null;
}
return null;
}
Here is my php code.
<html>
<body>
<?php
error_log("hit by app");
foreach($_POST as $key=>$value){
error_log("// ".$key." ".$value);
}
?>
</body>
</html>
Now in my apache log I see the "hit by app" message, but nothing else. And my app gets an empty html page with just the html and body tags as expected from the php code.
The problem I faced had to do with my URL. my url was like
http://ip_address/testbed
the page I was hitting was index.php inside the testbed directory. Since I didn't put trailing "/" apache wasn't sending the parameters to the page during the automatic redirect. Add the "/" resolved the issue. Thank you Sam_D for your help.
Is there a way to send android local HTML forms via ajax to remote php server? (local means the files are in my device) My scenario is this: In my app, I have an html files in my android device and is loaded in a webview, i also have the javascript file in my device. What i want to do is to send the html forms data to a remote server. In my current situation, its not sending any data, I've check the javascript and php and the code is fine, and it's working on iOS version of the app. I've tried other workarounds and what I've observed is that, when i load html file in webview using local files (e.g. webview.loadUrl("file://"+ Environment.getExternalStorageDirectory()+"/android_asset/list.html"), the android is looking for all other related files (e.g. formsprocessor.php) locally, though in javascript/ajax all necessary arguments in it's functions are supplied properly. The errors i've encountered are: FileNotFound: content://packagename.com/formsprocessor.php & Unknown chronium error: -6.
Is there a way or what is the best way to do this?
Thanks, Clint.
This solve my problem:
Used a javascripthandler, and in my javascript i call the function from the handler. So basically, the android handled the upload of data to server using httppost. Here's the codes;
the handler:
final class IJavascriptHandler{
IJavascriptHandler(){}
public void sendJSONToAndroid(String text){
if(!Config.canConnect((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE), home) && dialogNoConnFlag == false) {
dialogNoConnFlag = true;
Config.notificationMsg(Config.ERRORNOCONN,home, Config.TITLE1 + " " + Config.TITLE6);
return;
}
try {
Log.v("SendToServer","Send JSON to Server");
String url = "";
JSONObject json_data = new JSONObject(text);
JSONArray names= json_data.names();
JSONArray values = json_data.toJSONArray(names);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(int i = 0 ; i < values.length(); i++){
Log.v("Good",names.getString(i).toString());
if(names.getString(i).equals("url")) {
url = json_data.getString(names.getString(i)).toString();
}
nameValuePairs.add(new BasicNameValuePair( names.getString(i).toString(), json_data.getString(names.getString(i)).toString()));
}
Config.uploadToServer(nameValuePairs, url);
}
catch (JSONException e)
{
Config.notificationMsg(Config.ERRORMSG + e.getMessage(), (Activity) home, Config.TITLE1 + " " + Config.TITLE6);
}
}
}
the httppost:
public static String uploadToServer(List<NameValuePair> nameValuePairs, String url){
if(Session.isordinaryHost)
{
httpclient = new DefaultHttpClient();
}
else
{
httpclient = new MyHttpClient().getNewHttpClient();
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new AuthScope(Session.siteIp, 443),
new UsernamePasswordCredentials(Session.siteUsername, Session.sitePassword));
}
httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
EntityUtils.toString(entity);
}
catch (ClientProtocolException e)
{
return e.getMessage();
}
catch (IOException e)
{
return e.getMessage();
}
return null;
}
the javascript:
function CheckCompleteRecords() {
DB.transaction(function(tx) {
tx.executeSql(SelectCompleteForUploadStatement, [], function(tx, result) {
Dataset = result.rows;
for (var i = 0, item = null; i < Dataset.length; i++) {
item = Dataset.item(i);
var a = createJSON(item['FormName'],item['UserID'],item['Image1'],item['Image2'],item['Image3'],item['Image4'],item['Image5'],item['Field1'],item['Field2'],item['Field3'],item['Field4'],item['Field5'],item['Field6'],item['Field7'],item['Field8'],item['Field9'],item['Field10'],item['Field11'],item['Field12'],item['Field13'],item['Field14'],item['Field15'],item['Field16'],item['Field17'],item['Field18'],item['Field19'],item['Field20'],item['Field21'],item['Field22'],item['Field23'],item['Field24'],item['Field25'],item['Field26'],item['Field27'],item['Field28'],item['Field29'],item['Field30'],item['Field31'],item['Field32'],item['Field33'],item['Field34'],item['Field35'],item['Field36'],item['Field37'],item['Field38'],item['Field39'],item['Field40'],item['Field41'],item['Field42'],item['Field43'],item['Field44'],item['Field45'],item['Field46'],item['Field47'],item['Field48'],item['Field49'],item['Field50'],item['Field51'],item['Field52'],item['Field53'],item['Field54'],item['Field55'],item['Field56'],item['Field57'],item['Field58'],item['Field59'],item['Field60'],item['Field61'],item['Field62'],item['Field63'],item['Field64'],item['Field65'],item['Field66'],item['Field67'],item['Field68'],item['Field69'],item['Field70'],item['Field71'],item['Field72'],item['Field73'],item['Field74'],item['Field75'],item['Field76'],item['Field77'],item['Field78'],item['Field79'],item['Field80'],item['Field81'],item['Field82'],item['Field83'],item['Field84'],item['Field85'],item['Field86'],item['Field87'],item['Field88'],item['Field89'],item['Field90'],item['Field91'],item['Field92'],item['Field93'],item['Field94'],item['Field95'],item['Field96'],item['Field97'],item['Field98'],item['Field99'],item['Field100'],item['CurrentDateTime'],item['Geolocation'],item['BarCode']);
window.cpjs.sendJSONToAndroid(a);
showStuff('SendServerBtn');
window.location = "senttoserver://app_action";
}
});
});
}
I have connected database with phpliteadmin using xampp on localhost. Now I have to retrieve data from localhost and also to update it.. So any 1 can help me out from this problem..??
ok i have a function that sends some data to your local host and retrieve some data from there
use this method for communication :-
public void postData() throws Exception {
postData=et.getText().toString(); //some value
HttpClient httpclient = new DefaultHttpClient(); // connection
HttpPost httppost = new HttpPost("http://192.168.1.21/default.php"); //ip of your local host and php file!
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("msg", ""+str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
ResponseHandler<String> responseHandler=new BasicResponseHandler(); // to get the response printed there
String responseBody = httpclient.execute(httppost, responseHandler); // here we are recieving values.
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
and you can use this php coding to send and retrieve values :-
<?php
include ('MCrypt.php'); //this my encryption example
$thename=$_POST["msg"]; //get values from there using post and "msg" must be same on both side!
$mcrypt = new MCrypt();
$decrypted = $mcrypt->decrypt($thename);
echo("Your Encrypted String:--".$thename."\n"); // this line will be sent to android and will be recived in String Response;
echo("Your Decrypted String:--".$decrypted);
?>
can anyone give me an idea of using web service using HTTP protocol.
Here is an example for "Executing a HTTP POST Request with HttpClient":
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", "Paresh"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
We can use web services in our application to send and receive data from a remote server. Consider the case of an login section from a application where you need to pass username and password to the server for checking the whether the user is a valid user or not. In this case the username and password are attached with a url and send it to the remote server for validation and in response you get a value stating whether the user is a valid user or not. Usually the response will be either in XML format or JSON format from there we need to parse that response to get the necessary values. Check out the following example code in this I have created a class named "parsing" and it using the http protocol to receive a data.
public class parsing extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://services.digg.com/topics?appkey=http://example.com&type=json";
HttpPost post = new HttpPost(postURL);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
String response=EntityUtils.toString(resEntity);
response=response.trim();
Log.i("RESPONSE=",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See the response on the Logcat and do not for get to include <uses-permission android:name="android.permission.INTERNET" />
because we are fetching the data from the remote server which needs internet permission.