So I have this PHP code which makes a POST request to the specified URL. The $data array acts as a filter to apply to the request (for example to display the second page and maximum 10 items for that page). By default that values are "currentPage => 1" and "itemsPerPage => 100" (I'm accessing an API).
<?php
$usercode = '';
$username = '';
$password = '';
$URL = '';
$data =
array (
'currentPage' => 2,
'itemsPerPage' => 10
);
$hash = sha1(http_build_query($data) . sha1($password));
$requestData = array(
'code' => $usercode,
'username' => $username,
'data' => $data,
'hash' => $hash);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));
$result = curl_exec($ch);
$json_pretty = json_encode(json_decode($result), JSON_PRETTY_PRINT);
echo $json_pretty;
It works exactly as intended using PHP language, but I want to achieve the same behaviour in Java. The problem is that the filters doesn't apply (for every request the values of filters are ignored and the default values are used). I tried to make the request in the same form as in PHP, but for some reason the filters doesn't apply. This is my attempt using Apache's HttpClient:
public class Foo
{
private static String httpBuildQuery(List<? extends NameValuePair> parameters) {
return URLEncodedUtils.format(parameters, "UTF-8").replace("*", "%2A");
}
public static void main(String[] args)
{
String username = "";
String password = "";
String usercode = "";
final String URL = "";
String headerValueToBeEncoded = username + ":" + password;
String encodedHeaderValue = Base64.getEncoder().encodeToString(headerValueToBeEncoded.getBytes());
List<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("currentPage", "2"));
data.add(new BasicNameValuePair("itemsPerPage", "10"));
String passwordHash = DigestUtils.sha1Hex(password);
String dataQueryString = Foo.httpBuildQuery(data);
String valueToBeHashed = dataQueryString + passwordHash;
String hash = DigestUtils.sha1Hex(valueToBeHashed);
List<NameValuePair> requestData = new ArrayList<>();
requestData.add(new BasicNameValuePair("code", usercode));
requestData.add(new BasicNameValuePair("username", username));
requestData.add(new BasicNameValuePair("data", data.toString()));
requestData.add(new BasicNameValuePair("hash", hash));
String requestDataQueryString = Foo.httpBuildQuery(requestData);
try (CloseableHttpClient client = HttpClientBuilder.create().build())
{
HttpPost request = new HttpPost(URL);
request.setHeader("Authorization", "Basic " + encodedHeaderValue);
request.setEntity(new StringEntity(requestDataQueryString));
HttpResponse response = client.execute(request);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufReader.readLine()) != null)
{
builder.append(line);
builder.append(System.lineSeparator());
}
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i=0; i < jsonArray.length(); i++)
{
System.out.println(jsonArray.getJSONObject(i).get("id"));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The values of predefined that predefined strings (username, password, etc) have been left empty here because they contain sensitive information. In the last part I have printed only the values of the id's to check if the filters have been applied, but for every request the it prints 100 id's.
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 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;
}
I get the following error when trying to query an api in Java using HttpUrlConnection:
"Exception in thread "main" java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic MTk2YTVjODdhNWI2YjFmNWE3ZmQ5ODEtYjFjYTEzZmUtM2FkNC0xMWU1LWEyZjAtMDBkMGZlYTgy
NjI0OmY3NDQ2ZWQ0YjhjNzI2MzkyMzY1YzczLWIxY2ExNjQ4LTNhZDQtMTFlNS1hMmYwLTAwZDBm
ZWE4MjYyNA=="
Here is my code:
public class LocalyticsTest {
public static void main(String[] args) throws UnsupportedEncodingException {
String apiKey = "MyKey";
String apiSecret = "MySecretKey";
String apiUrl = "https://api.localytics.com/v1/query";
String credentials = apiKey + ":" + apiSecret;
//String encoding = Base64.encode(apiKey.getBytes("UTF-8"));
//String encoding2 = Base64.encode(apiSecret.getBytes("UTF-8"));
String encoding3 = new sun.misc.BASE64Encoder().encode (credentials.getBytes("UTF-8"));
String appId = "myAppId";
String metric = "sessions";
String dimensions = "day";
String condition = "'{\"day\":[\"between\",\"'.$newDate.'\",\"'.$newDate.'\"]}'";
Map data = new HashMap();
data.put("app_id", appId);
data.put("metric", metric);
data.put("dimensions", dimensions);
data.put("condition", condition);
QueryEncoder q = new QueryEncoder();
String newData = q.toQueryString(data);
String newUrl = String.format("%s?%s", apiUrl, newData);
try{
URL url = new URL(newUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
//conn.setRequestProperty("Authorization", "Basic");
//conn.setRequestProperty(apiKey,apiSecret);
conn.setRequestProperty("Authorization", "Basic " + encoding3);
conn.setRequestProperty("Accept", "application/vnd.localytics.v1+hal+json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am able to get it to work fine in php with Curl with the following:
function call_localytics_api($method, $url, $data)
{
$curl = curl_init();
$url = sprintf("%s?%s", $url, http_build_query($data));
$api_key = "myKey";
$api_secret = "mySecret";
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $api_key . ":" . $api_secret);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/vnd.localytics.v1+hal+json"));
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
$api_querystring = "https://api.localytics.com/v1/query";
$app_id = "myAppId";
$metric = "sessions";
$dimensions = "day";
//$data = array(app_id => $app_id, metrics => $metric, dimensions => $dimensions, conditions => '{"day":["in","'.$requestDate.'"]}');
$data = array(app_id => $app_id, metrics => $metric, dimensions => $dimensions, conditions => '{"day":["between","'.$newDate.'","'.$newDate.'"]}');
$response = call_localytics_api('GET', $api_querystring, $data);
$json = json_decode($response);
print_r($json);
Just need help getting it to work in Java.
It appears the illegal character is a newline. Use a base 64 encoder that doesn't put newlines in the result, or remove the newline yourself.
As of Java 8, you should use:
String encoding3 = Base64.getEncoder().encodeToString(
credentials.getBytes(StandardCharsets.UTF_8));
In older versions of Java, you can use DatatypeConverter:
String encoding3 = DatatypeConverter.printBase64Binary(
credentials.getBytes(StandardCharsets.UTF_8));
You could also remove the newline character directly, but you should use one of the above approaches instead. The sun.* classes are not for development use, and they can change or disappear from one Java release to the next. Furthermore, as I understand it, they may not even be usable at all as of Java 9, regardless of whether they exist, due to module restrictions.
Hello every one i am a junior php developer i am working on converting java code to php.. on Java api hit and get response correctly and now i am trying to hit using curl http post in php this is my task in my software house plz help me
i am gonna show you my java code which is correctly working and then my php code which is not working and not parsing params to that api so pls kindly guide me
This is my Java Code
This is working correctly i want to do this same work from php
import java.io.*;
import java.util.jar.JarException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
class MyCode{
public static void main(String[] args) throws JarException, JSONException
{
testCustomerApiIsExposed();
}
public static void testCustomerApiIsExposed() throws JarException, JSONException {
try {
#SuppressWarnings("deprecation")
HttpClient c = new DefaultHttpClient();
HttpPost p = new
HttpPost("http://link");
String payload = "{id:\"" + 1 + "\"," + "method:\"" + "customerApi.getApiToken" + "\", params:[\"teabonezenminddemo1partner#gmail.com\", \"demo1234!\", \"\", \"\", \"\", \"\", \"\", false, \"\", \"\"" + "]}";
String mimeType="";
/*There is something here. What constructor are we really calling here? */
// p.setEntity(new StringEntity( payload,ContentType.create("application/json")));
p.setEntity(new StringEntity(payload));
HttpResponse r = c.execute(p);
BufferedReader reader = new BufferedReader(new InputStreamReader(r.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener("[" + builder.toString() + "]");
JSONArray finalResult = new JSONArray(tokener);
JSONObject o = finalResult.getJSONObject(0);
//Getting names of the JSON object here
System.out.println(o.names());
String apiToken = (String) o.get("result");
System.out.println(apiToken);
}
catch(IOException e) {
System.out.println(e);
}
}
}
now i am coding this on php but don't get response check it pls and guide me i am using curl http post and getApiToken method help me to sort out this problem i am very tense.
This is my php code
<?php
$data = array(params);
$ch = curl_init('http://link');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
You are posting JSON from your java code. So use json here at PHP as well(make sure the format is ok):
$payload = "{params}";
And the curl options will be
// as you are posting JSON, so tell server that you are sending json
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
// Let server know that you are doing HTTP POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
Using these, I got sample response:
{"id":"1","result":"results"}
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>';
?>