我正在使用Android SO和Java开发应用程序。我想将一个xml文件作为POST发送到php服务器,它将xml中的信息插入到数据库中。
我该怎么做?
问候:D
答案 0 :(得分:1)
以下是如何使用Java
POST xmlString 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();
}
答案 1 :(得分:0)
将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
here的更多信息
在PHP中通过java从传递的xml文件中读取数据的代码
<?php
$dataPOST = trim(file_get_contents('php://input'));
$xmlData = simplexml_load_string($dataPOST);
print_r($xmlData);
?>
详细了解simplexml_load_string()
here
它只会在网页上打印xml数据作为响应。