繁体   English   中英

使用POST发送xml文件并在php中接收

[英]Send a xml file with POST and receive in php

我正在使用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.dir更多信息
通过PHP中的Java通过传递的xml文件读取数据的代码

<?php
$dataPOST = trim(file_get_contents('php://input'));
$xmlData = simplexml_load_string($dataPOST);    
print_r($xmlData);
?>

在此处阅读更多有关simplexml_load_string() 信息
它将仅在网页上打印xml数据作为响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM