I want to POST an XML file as DOM Document to a php page (received using Java).
When the Object is received in the php side. I read/traverse the file as a DOM Documents and send another XML DOcument file as response to the post.
Any directions would be very much appreciated.
Here's my sample Java code..
private Document sendToServerAndFetchResponse(Document xmlDocument) {
Document responseXML = null;
// Create the httpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// Url to which the post has to be performed.
HttpPost httppost = new HttpPost(
"http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");
// Make sure the server knows what kind of a response we will accept
httppost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httppost.addHeader("Content-Type", "application/xml");
try {
StringEntity entity = new StringEntity(xmlDocument.toString(),
"UTF-8");
entity.setContentType("application/xml");
httppost.setEntity(entity);
// execute is a blocking call, it's best to call this code in a
// thread separate from the ui's
HttpResponse response = httpClient.execute(httppost);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String strResponse = null;
if (response != null) {
try {
// Returns the response body as a String if the response was
// successful (a 2xx status code).
// If no response body exists, this returns null. If the
// response was unsuccessful (>= 300 status code), throws an
// HttpResponseException.
strResponse = responseHandler.handleResponse(response);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
return responseXML;
}
}
DOM is available in PHP, too. Your data (the request body) should be available as stdin. Here is a simple demo:
// create a dom and load the request body
$dom = new DOMDocument();
$dom->loadXml(file_get_contents('php://stdin'));
// create an xpath instance for the document
$xpath = new DOMXpath($dom);
// look for nodes and set the attribute
foreach ($xpath->evaluate('/foo/bar') as $node) {
$node->setAttribute('attr', 'success');
}
// send the header and output the document as string
header('Content-Type: application/xml');
echo $dom->saveXml();
Demo: https://eval.in/161089
You should recognize the methods of DOMDocument
from Javas xmlDocument
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.