2

How to write this code in php?

What i should use? CURL? fsockopen ? and what is actually send to server (outputString is a post / get and what its variable name)?

URL url = new URL(targetURL);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/xml");
conn.setDoOutput(true);

OutputStream out = conn.getOutputStream();
out.write(outputString.getBytes("UTF-8"));
out.close();

conn.connect();

final int code = conn.getResponseCode();
final String contentType = conn.getContentType();
final StringBuffer responseText = new StringBuffer();
InputStreamReader in = new InputStreamReader(conn.getInputStream(),"UTF-8");

char[] msg = new char[2048];
int len;
while ((len = in.read(msg)) > 0) {
    responseText.append(msg, 0, len);
}

Thank you for any answer.

1 Answer 1

1

This is a basic example of a cURL post...

Further reading at http://www.php.net/manual/en/function.curl-exec.php has very good examples too.

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.site.com/test.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "var1=value1&var2=value2&var3=value3");

// Get server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($result == "OK") { ... } else { ... }

?>

An example for SENDING XML:

<?php
    /**
     * Define POST URL and also payload
     */
    define('XML_PAYLOAD', '<?xml version="1.0"?><member><name>name</name></member>');
    define('XML_POST_URL', 'http://www.domain.com/build_xml.php');

    /**
     * Initialize handle and set options
     */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));

    /**
     * Execute the request and also time the transaction
     */
    $start = array_sum(explode(' ', microtime()));
    $result = curl_exec($ch);
    $stop = array_sum(explode(' ', microtime()));
    $totalTime = $stop - $start;

    /**
     * Check for errors
     */
    if ( curl_errno($ch) ) {
        $result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
    } else {
        $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        switch($returnCode){
            case 404:
                $result = 'ERROR -> 404 Not Found';
                break;
            default:
                break;
        }
    }

    /**
     * Close the handle
     */
    curl_close($ch);

    /**
     * Output the results and time
     */
    echo 'Total time for request: ' . $totalTime . "\n";
    echo $result;  

    /**
     * Exit the script
     */
    exit(0);
?>

And a 3rd for good measure, just to illustrate an alternative approach;

<?php
$xml     = '<request>Testing</request>';
$server  = '...'; // URL to server.php
$options = array 
(
    CURLOPT_URL            => $server,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $xml,
    CURLOPT_RETURNTRANSFER => true
);


$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);

echo '<pre>', htmlspecialchars($response), '</pre>';

?>
Sign up to request clarification or add additional context in comments.

3 Comments

Hi brian thanks for answer, on my above code is actually send serialized outputString. but i don't know what is send, i try to debug in my php server and i got nothing, but in java server it proceed successfully. unfortunately i cannot open the java server code.
OK in your example above it looks like it's sending XML. Have updated with example I refer to for myself.
thanks brian, i don't know if we can send post request with out any name on it. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.