I want to send data to my php page using android. How can I do it?
The Android API has a set of functions that allows you to use HTTP requests, POST, GET etc. In this example i will provide a set of code that will allow you to update the contents of a file in a server using POST requests.
Our server side code will be very simple and it will be written in PHP. The code will get data from a post request, update a file with the data and load this file to display it in a browser.
Create PHP page on server "mypage.php", the code for php page is:-
<?php
$filename="datatest.html";
file_put_contents($filename,$_POST["fname"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["fphone"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["femail"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["fcomment"]."<br />",FILE_APPEND);
$msg=file_get_contents($filename);
echo $msg; ?>
Create Android Project and write below code in HTTPExample.java
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/mypage.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("fname", "vinod"));
nameValuePairs.add(new BasicNameValuePair("fphone", "1234567890"));
nameValuePairs.add(new BasicNameValuePair("femail", "[email protected]"));
nameValuePairs.add(new BasicNameValuePair("fcomment", "Help"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With