【发布时间】:2010-04-06 09:52:33
【问题描述】:
我正在开发一个使用 Android SO 和 Java 的应用程序。我想将 xml 文件作为 POST 发送到 php 服务器,它将 xml 中的信息插入到数据库中。
我该怎么做?
问候:D
【问题讨论】:
-
你是问如何从手机发送或如何设置PHP来处理传入的数据?
-
如何处理de php接收java发送的xml...
我正在开发一个使用 Android SO 和 Java 的应用程序。我想将 xml 文件作为 POST 发送到 php 服务器,它将 xml 中的信息插入到数据库中。
我该怎么做?
问候:D
【问题讨论】:
以下是使用 Java 发布 xml 的方法
String urlText = "http://example.com/someservice.php";
String someXmlContent = "<root><node>Some text</node></root>";
try {
HttpURLConnection c = (HttpURLConnection) new URL(urlText).openConnection();
c.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream(), "UTF-8");
writer.write(someXmlContent);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
【讨论】:
将 XML 从 Java 发布到 PHP 的代码:
URL url = new URL("http://localhost/xml.php"); //your php file on localhost
String document = System.getProperty("user.dir")+"\\<your xml file name>";
FileReader fr = new FileReader(document);
char[] buffer = new char[1024*10];
int bytes_read = 0;
if((bytes_read = fr.read(buffer)) != -1){
URLConnection urlc = url.openConnection();
urlc.setRequestProperty("Content-Type","text/xml");
urlc.setDoOutput(true);
urlc.setDoInput(true);
//Now send xml data to your xml file
PrintWriter pw = new PrintWriter(urlc.getOutputStream());
pw.write(buffer, 0, bytes_read);
pw.close();
//Read response from php file
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
你可以阅读更多关于user.dirhere的信息
在 PHP 中通过 java 从传递的 xml 文件中读取数据的代码
<?php
$dataPOST = trim(file_get_contents('php://input'));
$xmlData = simplexml_load_string($dataPOST);
print_r($xmlData);
?>
阅读更多关于simplexml_load_string()here
它只会在网页上打印 xml 数据作为响应。
【讨论】: