Search code examples
javaphpweb-serviceshttpurlconnectionweb-deployment

Converting HTTP POST from curl (PHP) to HttpURLConnection (Java)


I tried to convert the below PHP code (taken from https://www.cryptocoincharts.info/tools/api) to java

// define pairs
$post = array("pairs" => "ltc_usd,ppc_btc");

// fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://api.cryptocoincharts.info/tradingPairs");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$rawData = curl_exec($curl);
curl_close($curl);

// decode to array
$data = json_decode($rawData);

// show data
echo "<pre>";
foreach ($data as $row)
{
    echo "Price of ".$row->id.": ".$row->price."\n";
    echo "Trade this pair on ".$row->best_market."\n";
}
echo "</pre>";

Java Code

    URL url = new URL("http://api.cryptocoincharts.info/tradingPairs");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    //  CURLOPT_POST
    con.setRequestMethod("POST");

    // CURLOPT_FOLLOWLOCATION
    con.setInstanceFollowRedirects(true);

    String postData = "ltc_usd,ppc_btc";
    con.setRequestProperty("Content-length", String.valueOf(postData.length()));

    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());
    output.writeBytes(postData);
    output.close();

    // "Post data send ... waiting for reply");
    int code = con.getResponseCode(); // 200 = HTTP_OK
    System.out.println("Response    (Code):" + code);
    System.out.println("Response (Message):" + con.getResponseMessage());

    // read the response
    DataInputStream input = new DataInputStream(con.getInputStream());
    int c;
    StringBuilder resultBuf = new StringBuilder();
    while ( (c = input.read()) != -1) {
        resultBuf.append((char) c);
    }
    input.close();
    System.out.println("resultBuf.toString() " + resultBuf.toString());

As per the API, after converting this to java I should get only the details of LTC and PPC details. Instead I am getting a strange Json with all trading pairs.

2 $post = array("pairs" => "ltc_usd,ppc_btc"); Posted the PHP code as I am not known the exact equivalent in Java

Could you please point out if my conversion from PHP to Java is correct ?


Solution

  • As far as I see, the main difference between the two implementation is related to the $post variable.

    In the PHP implementation $post is a key/value array but in Java I only see the value part.

    I suggest to change the postData variable content into pairs=ltc_usd,ppc_btc