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;
}
Related
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.
I'm struggling with HttpURLConnection and OutputStreamWriter.
The code actually reaches the server, as I do get a valid error
response back. A POST request is made, but no data is received
server-side.
Any hints to proper usage of this thingy is highly appreciated.
The code is in an AsyncTask
protected JSONObject doInBackground(Void... params) {
try {
url = new URL(destination);
client = (HttpURLConnection) url.openConnection();
client.setDoOutput(true);
client.setDoInput(true);
client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
client.setRequestMethod("POST");
//client.setFixedLengthStreamingMode(request.toString().getBytes("UTF-8").length);
client.connect();
Log.d("doInBackground(Request)", request.toString());
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
String output = request.toString();
writer.write(output);
writer.flush();
writer.close();
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("doInBackground(Resp)", result.toString());
response = new JSONObject(result.toString());
} catch (JSONException e){
this.e = e;
} catch (IOException e) {
this.e = e;
} finally {
client.disconnect();
}
return response;
}
The JSON I'm trying to send:
JSONObject request = {
"action":"login",
"user":"mogens",
"auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7",
"location":{
"accuracy":25,
"provider":"network",
"longitude":120.254944,
"latitude":14.847808
}
};
And the response I get from the server:
JSONObject response = {
"success":false,
"response":"Unknown or Missing action.",
"request":null
};
And the response I should have had:
JSONObject response = {
"success":true,
"response":"Welcome Mogens Burapa",
"request":"login"
};
The server-side PHP script:
<?php
$json = file_get_contents('php://input');
$request = json_decode($json, true);
error_log("JSON: $json");
error_log('DEBUG request.php: ' . implode(', ',$request));
error_log("============ JSON Array ===============");
foreach ($request as $key => $val) {
error_log("$key => $val");
}
switch($request['action'])
{
case "register":
break;
case "login":
$response = array(
'success' => true,
'message' => 'Welcome ' . $request['user'],
'request' => $request['action']
);
break;
case "location":
break;
case "nearby":
break;
default:
$response = array(
'success' => false,
'response' => 'Unknown or Missing action.',
'request' => $request['action']
);
break;
}
echo json_encode($response);
exit;
?>
And the logcat output in Android Studio:
D/doInBackground(Request)﹕ {"action":"login","location":{"accuracy":25,"provider":"network","longitude":120.254944,"latitude":14.847808},"user":"mogens","auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7"}
D/doInBackground(Resp)﹕ {"success":false,"response":"Unknown or Missing action.","request":null}
If I append ?action=login to the URL I can get a success response from the server. But only the action parameter registers server-side.
{"success":true,"message":"Welcome ","request":"login"}
The conclusion must be that no data is transferred by URLConnection.write(output.getBytes("UTF-8"));
Well, data get transferred after all.
Solution offered by #greenaps does the trick:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
PHP script above updated to show the solution.
echo (file_get_contents('php://input'));
Will show you the json text. Work with it like:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
try to use DataOutputStream instead of OutputStreamWriter.
DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
out.writeBytes(your json serialized string);
out.close();
I've made server tell me what it got from me.
Request Headers and POST Body
<?php
$requestHeaders = apache_request_headers();
print_r($requestHeaders);
print_r("\n -= POST Body =- \n");
echo file_get_contents( 'php://input' );
?>
Works like a charm)
The code actually reaches the server, as I do get a valid error
response back. A POST request is made, but no data is received
server-side.
got this same situation, and come to #greenapps answer.
you should know what server recieved from 'post request'
what i do first on the server side :
echo (file_get_contents('php://input'));
then print/Toast/show message response on the client side. make sure its correct form, like :
{"username": "yourusername", "password" : "yourpassword"}
if the response like this (because you post the request with yourHashMap.toString()) :
{username=yourusername,password=yourpassword}
instead using .toString(), use this method instead to turn HashMap into String :
private String getPostDataString(HashMap<String, String> postDataParams) {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String,String> entry : postDataParams.entrySet()){
if(first){
first = false;
}else{
result.append(",");
}
result.append("\"");
result.append(entry.getKey());
result.append("\":\"");
result.append(entry.getValue());
result.append("\"");
}
return "{" + result.toString() + "}";
}
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();
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?
I have an applet (not our choice, it's the MarioAI engine) that I'd like to connect to a node.js app that uses express...but I can't seem to get mongodb to accept the values I'm sending in my POST request through localhost. I keep getting 200 response from node, but 'undefined' from mongooose, which I suspect means the URLEncoder I'm using in Java is mangling the String I'm sending through somehow.
I read this:
Problem with Java Applet to connect our server to call a PHP file
and tried the following OutputStreamWriter call in Java:
//EvaluateFrustration() takes an int but should come back with a float value
String frustrationString = Double.toString(EvaluateFrustration(this.periods));
try {
URL url = new URL("http://127.0.0.1:8888/mario");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
System.out.println(conn.getResponseCode());
conn.setUseCaches (false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter writer;
writer = AccessController
.doPrivileged(new PrivilegedExceptionAction<OutputStreamWriter>() {
public OutputStreamWriter run() throws IOException {
return new OutputStreamWriter(conn.getOutputStream());
}
});
String data = URLEncoder.encode("frustrationValueFirstRound="
+ frustrationString,"UTF-8");
writer.write(data);
writer.flush();
} catch (Exception e) {
}
In the node app (using express and mongoose/mongodb), I wrote:
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ExperimentSchema = new Schema({
experiment : ObjectId
, frustrationValueFirstRound : Number
});
mongoose.connect('mongodb://localhost/mariopaper');
mongoose.model('Experiment', ExperimentSchema);
var Experiment = mongoose.model('Experiment');
app.post('/mario', function(req, res){
var exp = new Experiment();
exp.frustrationValueFirstRound = req.body.frustrationValueFirstRound;
exp.save(function(err){ if (err) { throw err; }
res.send('ok');
});
For reference, I'd like to point out that this curl call works just fine:
curl -d "frustrationValueFirstRound=99" http://localhost:8888/mario
Anyone have any ideas whether I've simply written the POST wrong in Java, or perhaps I'm missing something in how URLEncoder.encode() works?
I think that's because you don't have the body-parser node module, that "Parse incoming request bodies in a middleware before your handlers, available under the req.body property."
Try this (after installing body-parser module):
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ExperimentSchema = new Schema({
experiment : ObjectId
, frustrationValueFirstRound : Number
});
mongoose.connect('mongodb://localhost/mariopaper');
mongoose.model('Experiment', ExperimentSchema);
var Experiment = mongoose.model('Experiment');
app.post('/mario', function(req, res){
console.log(req.body); // Is there something here ?
var exp = new Experiment();
exp.frustrationValueFirstRound = req.body.frustrationValueFirstRound;
exp.save(function(err){ if (err) { throw err; }
res.send('ok');
});
source : https://github.com/expressjs/body-parser