【发布时间】:2011-04-14 16:03:41
【问题描述】:
我想使用 android 将数据发送到我的 php 页面。我该怎么做?
【问题讨论】:
我想使用 android 将数据发送到我的 php 页面。我该怎么做?
【问题讨论】:
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"/>
【讨论】:
您可以使用AndroidHttpClient 发出 GET 或 POST 请求:
This answer 似乎是一个相当完整的代码示例。
【讨论】:
这里给出了一个 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) {
}
【讨论】: