Convert PHP curl request to Java












0















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.










share|improve this question























  • can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

    – Saidolim
    Nov 22 '18 at 19:10











  • @Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

    – Cristian Coroian
    Nov 22 '18 at 19:53











  • Can you give example of response from server? Difficult to understand what you have and what you want to see.

    – Saidolim
    Nov 22 '18 at 19:56











  • @Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

    – Cristian Coroian
    Nov 23 '18 at 7:19











  • As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

    – Saidolim
    Nov 23 '18 at 7:36
















0















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.










share|improve this question























  • can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

    – Saidolim
    Nov 22 '18 at 19:10











  • @Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

    – Cristian Coroian
    Nov 22 '18 at 19:53











  • Can you give example of response from server? Difficult to understand what you have and what you want to see.

    – Saidolim
    Nov 22 '18 at 19:56











  • @Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

    – Cristian Coroian
    Nov 23 '18 at 7:19











  • As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

    – Saidolim
    Nov 23 '18 at 7:36














0












0








0








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.










share|improve this question














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.







java php curl






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 18:34









Cristian CoroianCristian Coroian

33




33













  • can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

    – Saidolim
    Nov 22 '18 at 19:10











  • @Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

    – Cristian Coroian
    Nov 22 '18 at 19:53











  • Can you give example of response from server? Difficult to understand what you have and what you want to see.

    – Saidolim
    Nov 22 '18 at 19:56











  • @Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

    – Cristian Coroian
    Nov 23 '18 at 7:19











  • As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

    – Saidolim
    Nov 23 '18 at 7:36



















  • can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

    – Saidolim
    Nov 22 '18 at 19:10











  • @Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

    – Cristian Coroian
    Nov 22 '18 at 19:53











  • Can you give example of response from server? Difficult to understand what you have and what you want to see.

    – Saidolim
    Nov 22 '18 at 19:56











  • @Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

    – Cristian Coroian
    Nov 23 '18 at 7:19











  • As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

    – Saidolim
    Nov 23 '18 at 7:36

















can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

– Saidolim
Nov 22 '18 at 19:10





can you try like this: for(JSONObject jsonObject : jsonArray) { System.out.println(jsonObject.get("id")); }

– Saidolim
Nov 22 '18 at 19:10













@Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

– Cristian Coroian
Nov 22 '18 at 19:53





@Saidolim I don't think it matters if I use foreach or a normal for to iterate through the JSON.

– Cristian Coroian
Nov 22 '18 at 19:53













Can you give example of response from server? Difficult to understand what you have and what you want to see.

– Saidolim
Nov 22 '18 at 19:56





Can you give example of response from server? Difficult to understand what you have and what you want to see.

– Saidolim
Nov 22 '18 at 19:56













@Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

– Cristian Coroian
Nov 23 '18 at 7:19





@Saidolim I see what I want to see because I get a successful response from the server. The problem is that I don't see enough results because the filters doesn't apply. May be something with the query string.

– Cristian Coroian
Nov 23 '18 at 7:19













As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

– Saidolim
Nov 23 '18 at 7:36





As I understand. for hashing your data you use Replace funstin in URLEncodedUtils.format(parameters, "UTF-8").replace("", "%2A"); but in sending parameters you also use .replace("", "%2A"); I thinks you have to use without replace in 2nd time for requestDataQueryString. You have to check, what is including on Request.

– Saidolim
Nov 23 '18 at 7:36












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436540%2fconvert-php-curl-request-to-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436540%2fconvert-php-curl-request-to-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Futebolista

Feedback on college project

Albești (Vaslui)