Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

php - How to send a data to a web server from Android

I want to send data to my php page using android. How can I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...