Jonas
Jonas

Reputation: 128807

How can I send XML from a Java application and print it with PHP on the server, using HTTP POST?

Usually when I get POST data it's send from a HTML form and the parameters has names, i.e. from <input type="text" name="yourname" />, then I can receive and print this data with php echo $_POST['yourname'];.

Now I am implementing a Java application that should POST data in XML format to a specified URL. I wrote a simple PHP page that I can try to POST data to, but the data is not printed. And since there is no name of any parameters I don't know how I should print it with PHP.

I have tried to send simple XML to the server and the server should respond with MESSAGE: <XML>, but it only response with MESSAGE:. What am I doing wrong?

Here is my PHP-code on the server:

<?php 
echo 'MESSAGE:';
print_r($_POST); ?>

And here is my Java code on the client:

String xmlRequestStatus = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
    <test></test>";
String contentType = "text/xml";
String charset = "ISO-8859-1";
String request = null;
try {
    request = String.format("%s",
        URLEncoder.encode(xmlRequestStatus, charset));
} catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}
URL url = null;
URLConnection connection = null;
OutputStream output = null;
InputStream response = null;
try {
    url = new URL("http://skogsfrisk.se/test/");
} catch (MalformedURLException e) {
    e.printStackTrace();
}

try {
    connection = url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", contentType);
    output = connection.getOutputStream();
    output.write(request.getBytes("ISO-8859-1"));
    if(output != null) try { output.close(); } catch (IOException e) {}

    response = connection.getInputStream();
    ...
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 1

Views: 1375

Answers (2)

rook
rook

Reputation: 67019

Try viewing the page's source in your browser after you post the xml, the xml isn't going to show up if you are viewing the page normally unless you pass it to htmlspecialchars(). print_r($_POST); is xss so be careful.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157864

No, $_POST array is being populated only with multipart/form-data enctype.

you can use either fopen() with php://input wrapper or $HTTP_RAW_POST_DATA
http://www.php.net/manual/en/wrappers.php.php

Upvotes: 3

Related Questions