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

4

我想使用安卓将数据发送到我的PHP页面。我该怎么做?

3个回答

12

Android API提供了一组函数,允许您使用HTTP请求、POST、GET等操作。 在本示例中,我将提供一组代码,使您能够使用POST请求更新服务器上文件的内容。

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

在服务器上创建PHP页面"mypage.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,并编写以下代码。

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

我对你的代码有一些问题,不幸的是它们已经关闭了。我已经完全插入了互联网许可,你能否在你的代码中添加更多内容?为什么我会收到错误并且值没有发送到服务器? - Amitsharma

6

4
这里给出一个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) {
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接