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

时间:2011-04-14 16:03:41

标签: php android

我想使用android将数据发送到我的php页面。我该怎么办?

3 个答案:

答案 0 :(得分: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; ?>

创建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
     }

在AndroidManifest.xml中添加权限

    <uses-permission android:name="android.permission.INTERNET"/>

答案 1 :(得分:6)

您可以使用AndroidHttpClient生成GET或POST请求:

  1. 创建AndroidHttpClient以执行您的请求。
  2. 创建HttpGetHttpPost请求。
  3. 使用setEntitysetHeader方法填充请求。
  4. 根据您的请求,在您的客户端上使用execute方法之一。
  5. This answer似乎是一个相当完整的代码示例。

答案 2 :(得分:3)

此处给出了HTTP POST请求的快速示例:

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}