Solved

Using PHP Curl to post data to Java Servlet

Posted on 2010-09-09
8
3,493 Views
Last Modified: 2012-05-10
Hi,

I've been toying around with something over the last few days but can't quite get it to work. Wondering if anyone can help me.

I have a Java servlet running on Tomcat (this is all on my local machine for testing purposes). This servlet accepts one variable (a block of XML) and returns another block of XML as a result. The servlet is running fine (I can test it through my browser and even POST successfully to it from a PHP form receiving the correct XML block as result). What I want to be able to do post the data and access the result with curl.

Here is my current code -

$xml='<result><name>bob</name></result>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/myServer/TestServlet" );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt ($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);

curl_close($ch);

$xmlResult = file_get_contents($postResult);
var_dump($xmlResult);

I want to be able to read $xmlResult. Everytime I try to run this, I get an error message that the posted data is empty. What am I doing wrong? Is there an alternative to curl that I could be using?

Thanks in advance

0
Comment
Question by:dosser
  • 3
  • 3
  • 2
8 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 33638161
Can't look at this till later today, but here is a CURL POST example that works for me.  Feel free to post your data to my bounce script.
<?php // RAY_curl_post_example.php
error_reporting(E_ALL);

function curl_post($url, $post_array, $timeout=2, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = '';
    foreach ($post_array as $key => $val)
    {
        $post_string .= urlencode($key) . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,            $url);
    curl_setopt($curl, CURLOPT_HEADER,         FALSE);
    curl_setopt($curl, CURLOPT_POST,           TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS,     $post_string);
    curl_setopt($curl, CURLOPT_TIMEOUT,        $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);
    curl_close($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            echo "<pre>\n";
            var_dump($inf);
            echo "</pre>\n";
        }
        return FALSE;
    }

    // ON SUCCESS
    return $htm;
}

// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["name"]  = 'Ray';
$args["email"] = 'Ray.Paseur@Gmail.com';

// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
// var_dump($args);

// SET THE URL
$url = "http://LAPRBass.com/RAY_bounce_post.php";

// CALL CURL TO POST THE EATA
$htm = curl_post($url, $args, 3, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT CAME BACK
echo "<pre>";
echo htmlentities($htm);

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 33638170
Here is what the bounce post script does.
<?php // RAY_bounce_post.php
error_reporting(E_ALL);

// START A BUFFER TO CAPTURE THE BROWSER OUTPUT
ob_start();

// SHOW WHAT WAS RECEIVED IN POST
var_dump($_POST);

// CAPTURE THE BUFFER
$posted_data = ob_get_clean();

// SAY THANK YOU
echo "<pre>";
echo "THANK YOU " . date('c');
echo PHP_EOL;
echo $posted_data;

Open in new window

0
 

Author Comment

by:dosser
ID: 33638411
The problem is that I need to post a block of XML (so can't really fill the array with key/value pairs). Or can you really use the string e.g http://localhost:8080/myServer/TestServlet?queryxml=<result><name>bob</name></result>

I only gave a simple example in the original post but the XML block I actually need to send is quite complicated.
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 6

Expert Comment

by:DalHorinek
ID: 33639103
How do you manually send request to server? Post an example.
0
 

Author Comment

by:dosser
ID: 33639372
I use a php page with a textarea. I input the XML in the textarea, click submit, and the correct XML result block is returned -

<?php

echo'
<form method="post" action="http://localhost:8080/myServer/TestServlet">
<textarea name="inputXml"></textarea>
<input type="submit">
</form> ';

?>

Should I be using a key/value pair of inputXml -> $xml (where $xml is a huge block of the XML to be posted)? Or will that not work?

0
 
LVL 6

Accepted Solution

by:
DalHorinek earned 500 total points
ID: 33639457
yes, you need to post:

inputXml=<result>...</result>
0
 

Author Comment

by:dosser
ID: 33639517
Thanks Dal. A combo of that and urlencode did the job.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 33641280
Sorry, but I had to go out to my club for lunch so I couldn't follow this Q until now.  

Regarding this, "so can't really fill the array with key/value pairs..."

That's not much of an issue.  Consider this string:
inputXml=<result>...</result>

With a little creativity you might find that this array would be right:
$postarray = array("inputXml" => "<result>...</result>");

Or with a little more creativity, you could just bypass the code that converts the array to a raw post string.  The examples I post here are just that -- examples, not meant to represent final code, just a standard practices example of a solution.  The main reason that an array is present in the example is because most people understand COOKIE, GET and POST arguments in terms of an associative array.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question