What will be the equivalent to following curl command in java - java

i need to convert the following curl command into java command.
$curl_handle = curl_init ();
curl_setopt ($curl_handle, CURLOPT_URL,$url);`enter code here`
curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl_handle, CURLOPT_POST, 1);
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postfields);
//echo $postfields;
$curl_result = curl_exec ($curl_handle) or die ("There has been a CURL_EXEC error");

Http(s)UrlConnection may be your weapon of choice:
public String sendData() throws IOException {
// curl_init and url
URL url = new URL("http://some.host.com/somewhere/to/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// CURLOPT_POST
con.setRequestMethod("POST");
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData = "my_data_for_posting";
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();
return resultBuf.toString();
}
I'm not quite sure about the HTTPS_VERIFYPEER-thing, but this may give you a starting point.

Have a look at the java.net.URL and java.net.URLConnection libraries.
URL url = new URL("yourUrl.com");
Then use a an InputStreamReader & BufferedReader.
More information in Oracles example: http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
This might also help: How to use cURL in Java?

Related

Android POST Request Not Working Properly

I am using the following method for getting time from server with a Post request.
String result = "";
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.118.2/myapi");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("time", "UTF-8")
+ "=" + URLEncoder.encode("Submit", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String line = "";
while((line = reader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
Here is php script
<?php
if(isset($_POST["time"]))
echo "Time";
else
echo "Invalid Request";
But when i call post method, i get resut "Invalid Request".
I almost searched every stackoverflow threads but none of them working, i really wonder what is the problem.
A few things to try.
1) Add the following to your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2) change your PHP file
<?php
$time = urldecode($_POST['time']);
if($time === NULL) {
echo "invalid";
} else {
echo "time";
}
?>
I fixed the problem with following changes;
data = "time=Submit";
...
...
...
url = new URL("http://192.168.118.2/myapi/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setInstanceFollowRedirects( false );
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( data.getBytes().length ));
urlConnection.setUseCaches( false );
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
...
...
...

how can i convert from php curl to java

I am looking to try convert curl to JAVA code. cURL code in php work perfect but in java theres porblem this is code php
$urlt="http://api.xxxxxxx/xxxxx";
$apikey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$camp="id";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$urlt);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey' => $apikey, 'apif' => 'ge', 'camp' => $camp));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
and this is my convert to java
String apikey="xxxxxxx";
String camp="17";
URL url = new URL("http://xxxxxxx/xxxxxxxx");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(true);
String postData = "apikey"+apikey+"apif=ge"+"camp"+camp; // I need somthing like this
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();
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ( (c = input.read()) != -1) {
resultBuf.append((char) c);
}
input.close();
return resultBuf.toString();
and this is the out put
Response (Code):200
Response (Message):OK
API KEY REQUIRED
You're not encoding your parameters correctly. You're missing an = and the & separators:
"apikey="+apikey+"&apif=ge"+"&camp="+camp
If there's a way of having the library do the encoding for you, as you do in the CURL example using an array(...), that's usually a lot safer.

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 ?
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
You didn't mentioned key part, only value is mentioned. And when we fetch data from PHP API, we have an associative array. If u want to display the output, u need to know the key and value of the particular associative array.
And the InputStream and OutputStream should be inside try-resources
you can try curl-to-java lib to convert curl php code to java code
https://github.com/jeffreyning/curl-to-java
demo like this
public Object curl(String url, Object postData, String method) {
CurlLib curl = CurlFactory.getInstance("default");
ch = curl.curl_init();
curl.curl_setopt(ch, CurlOption.CURLOPT_CONNECTTIMEOUT, 1000);
curl.curl_setopt(ch, CurlOption.CURLOPT_TIMEOUT, 5000);
curl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYPEER, false);
curl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYHOST, false);
String postDataStr = "key1=v1";
curl.curl_setopt(ch, CurlOption.CURLOPT_CUSTOMREQUEST, "POST");
curl.curl_setopt(ch, CurlOption.CURLOPT_POSTFIELDS, postDataStr);
curl.curl_setopt(ch, CurlOption.CURLOPT_URL, "https://xxxx.com/yyy");
Object html = curl.curl_exec(ch);
Object httpCode = curl.curl_getinfo(ch, CurlInfo.CURLINFO_HTTP_CODE);
if (httpCode != null && 200 == Integer.valueOf(httpCode.toString())) {
return null;
}
return html;
}

Execute terminal command in java with httpurlconnection and get response in json format

I have a localhost server running on port 4000 which listens to requests sent to it and executes commands and returns output to client in a json format.
I'm trying to send a request from tomcat's port 8080 to it and i need it to execute a command and send output back in json format.
I was able to do it through php using curl and the command executed but I need the solution in java so I made the following code:
public String sendData() throws IOException {
// curl_init and url
URL url = new URL("http://localhost:4000");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// CURLOPT_POST
con.setRequestMethod("POST");
// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);
String postData = "ls"; //just trying a simple command
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();
return resultBuf.toString();
}
I'm getting a response "OK" and the default output of the port 4000. But the command doesn't execute.
Any idea what I'm missing? Or doing wrong?
Edit on popular demand: The php curl function
protected function HTTPRequest($url, $command){
//open connection
$ch = curl_init();
$fields['command'] = $command;
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
$url here is http://localhost:4000
and $command is just any command is passed.
Your OutputStream cannot call any terminal command, because it's bound to your http connection only. To run terminal commands from the jvm, you can use Runtime.getRuntime().exec
As an alternative you can use Apache Commons Exec, which I prefer.
Easiest way for you is to call your command in your function sendData(). Do it like this:
StringBuffer output = new StringBuffer();
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
// your output that you can use to build your json response:
output.toString();

Java URLConnection to php

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.
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>';
?>

Categories

Resources