如何从Android向Web服务器发送数据

bha*_*h N 4 php android

我想用android将数据发送到我的php页面.我该怎么做?

vin*_*oft 11

Android API有一组函数,允许您使用HTTP请求,POST,GET等.在这个例子中,我将提供一组代码,允许您使用POST请求更新服务器中文件的内容.

我们的服务器端代码非常简单,它将用PHP编写.代码将从post请求中获取数据,使用数据更新文件并加载此文件以在浏览器中显示它.

在服务器"mypage.php"上创建PHP页面,php页面的代码是: -

 <?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; ?>
Run Code Online (Sandbox Code Playgroud)

创建Android项目并在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", "abc@gmail.com"));
       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
     }
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest.xml中添加权限

    <uses-permission android:name="android.permission.INTERNET"/>
Run Code Online (Sandbox Code Playgroud)


Mat*_*lis 6

您可以使用AndroidHttpClient发出GET或POST请求:

  1. 创建一个AndroidHttpClient来执行您的请求.
  2. 创建HttpGetHttpPost请求.
  3. 使用setEntitysetHeader方法填充请求.
  4. 根据您的请求,在您的客户端上使用其中一种执行方法.

这个答案似乎是一个相当完整的代码示例.