【问题标题】:Send a xml file with POST and receive in php使用 POST 发送 xml 文件并在 php 中接收
【发布时间】:2010-04-06 09:52:33
【问题描述】:

我正在开发一个使用 Android SO 和 Java 的应用程序。我想将 xml 文件作为 POST 发送到 php 服务器,它将 xml 中的信息插入到数据库中。

我该怎么做?

问候:D

【问题讨论】:

  • 你是问如何从手机发送或如何设置PHP来处理传入的数据?
  • 如何处理de php接收java发送的xml...

标签: java php android


【解决方案1】:

以下是使用 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();
} 

【讨论】:

  • 你能告诉我我是如何在 php 服务器中收到这篇文章的吗?
【解决方案2】:

将 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 数据作为响应。

【讨论】:

  • 我是stackoverflow的新手,感谢编辑,现在看起来好多了!!!
猜你喜欢
  • 2017-05-31
  • 1970-01-01
  • 2011-11-06
  • 2023-02-05
  • 2011-02-18
  • 2016-02-22
  • 2012-03-11
  • 2016-11-30
  • 1970-01-01
相关资源
最近更新 更多