开发者

Send a xml file with POST and receive in php

开发者_如何学C

I'm working on an application using Android SO and Java. I would like to send an xml file as POST to a php server, that inserts the information from the xml into a database.

how can i do that?

regards :D


Here's how to POST xml with Java

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();
} 


Code to post XML from Java to 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();                
}

You may read more about user.dir here
Code to read data from passed xml file through java in PHP

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

Read more about simplexml_load_string() here
It will simply print xml data on web page as response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜