How to run a curl command from java? [duplicate] - java

This question already has an answer here:
Using curl command in java
(1 answer)
Closed 4 years ago.
I am trying to make a POST request from Java using curl. It also has some payload. I am getting status code 400. What am I missing?
Following is the curl I use in terminal..
curl --cookie "token=xyzxyzxyzxyz" --header "Content-Type:application/json" --data
{"branchName":"name","branchId":"bid","sourceBranch":"sb","alias":"pppp","mainPackageFullPath":"main.full.path"}'
-k http://app.aws.application/api/random/create

You can do it like this
String branchName="name";
String branchId="bid";
String sourceBranch="sb"
String alias="ppp"
String[] command = {"curl" "-k" "-i" "-X" POST "-H" "Content-Type: multipart/form-data" --cookie "rsession=your rsession" "Content-Type:application/json" --data{branchName+":"+branchId":"+sourceBranch":",+alias}};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try
{
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.print(result);
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}

Related

Pass Blank space in Json value in curl command string in Java

I am sending a POST request using curl command string in Java. I am passing json in the command string which has spaces in the values. I am getting an error when compiler encounters space in json. I need to retain spaces and pass the values in the string curl command. Please help. i would be great if someone can re-write my string[] command to help me understand my mistake. Here is my code.
String[] command = { "curl", "-X", "POST", "http://my.url.com/add", "-H", "accept: application/json", "-H", "AuthorizationToken: 123", "-H", "Content-Type: application/json", "-d", "{\"FieldLabels\":\"Name,Status,Employee number\",\"FieldValues\":\"test7,Planned,Raj Kumar(123)\",\"Type\":\"BT\"}" };
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try
{
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.print(result);
}
catch (Exception e)
{
e.printStackTrace();
}
Error:
{
"message" : {
"statusCode" : "500",
"Status" : "Internal Server Error",
"requestedURI" : "/api/EFormService/createEFormItemData",
"error" : "Expected a ':' after a key at character 25 of {FieldLabels:Name,Status,Employee"
}
}
Try to place the json request in a file and use the below format in the curl request
--data "#<path/to/file>"
'#' represent the request data is in a file in the path follows.
for your example:
data:
{"FieldLabels":"Name,Status,Employee
number","FieldValues":"test7,Planned,Raj Kumar(123)","Type":"BT"}
this data need to be saved into a file eg: /tmp/reqData
then below is your command
{ "curl", "-X", "POST", "http://my.url.com/add", "-H", "accept: application/json", "-H", "AuthorizationToken: 123", "-H", "Content-Type: application/json", "-d", "#/tmp/reqData" };
i have created JSON object, opened a connection with httpurlconnection, set header parameters and pass jason object in body. it worked. Thanks Sarath.

Curl command through Java works in windows and not in linux

I am trying to execute a curl command using Java using the code below
String myUrl= "https://someIp:somePort";
String username = "someusername";
String password = "somepassword";
String command = "curl -k -d \"client_id=someId\" -d \"username="+username+"\" -d \"password="+password+"\" -d \"grant_type=password\" -d \"client_secret=\" \""+myUrl+"/myauth/openid-connect/token\"";
Process process = Runtime.getRuntime().exec(command);
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = process.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String response = result.toString(StandardCharsets.UTF_8.name());
This works on windows machine but not on linux. Is there any difference between linux and windows in the way curl command is executed using exec method ?
Both execution are done using same JRE. On windows I get the token successfully but in Linux I get the following response :
Response = {"error":"invalid_request","error_description":"Missing form parameter: grant_type"}
Thank you
After investigation it seems that when someone executes this java code in linux enviroment the curl command is not properly constructed.
I used the following code and everything worked fine :
String cUrlToKeyCloak = "curl -k -d \"client_id=someId\" -d \"username="+username+"\" -d \"password="+password+"\" -d \"grant_type=password\" "+keyCloakUrl+"/auth/realms/master/protocol/openid-connect/token";
ProcessBuilder processBuilder = new ProcessBuilder();
if(!System.getProperty("os.name").contains("Windows"))
processBuilder.command("bash", "-c", cUrlToKeyCloak );
else
processBuilder.command("cmd.exe", "/c", cUrlToKeyCloak );
String cKeyResponse = "";
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
LOGGER.info("Curl command to keyCloak requested ...");
LOGGER.info("cKey response = "+output);
cKeyResponse = output.toString();
} else {
LOGGER.error("Curl command to keyCloak executed with error ...");
LOGGER.info("cKey response = "+output);
return false;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

Execute Curl from Java

I am trying to execute the following curl command from Java, but the answer I get is incorrect, since it always returns the status 401.
curl -k -v -u "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" -d "{"username":"test","token_code":"246212"}" -H "Content-Type: application/json" https://192.168.101.59/api/v1/auth/
I am sending correctly the user "admin2" with his password for the authentication. I think the problem is the use of character (") in my code.
String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
"-d", "{\"username\":\"test\",\"token_code\":\"246212\"}","-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
String curlResult = "";
String line = "";
try {
Process process = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
curlResult = curlResult + line;
}
} catch (Exception e) {
e.printStackTrace();
}
In 'command', try removing the single quotes from
"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"
so that it becomes
"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"
and see if that helps. It might be considering them as part of the actual username and password.
I think the issue is the Json in this case and I think you are right then that the double quotes are the issue. Try putting the Json in a file and use curl to send the file contents as the body of your message.
String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
"-d", "#/path/to/filename.json", "-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};

How to get processbuilder command before execution

I want to know the command that will be executed before it happens.
String cmd[] = {"curl",
"-X",
"POST",
"https://api.renam.cl/medicion/insert?access-token={Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD}",
"-H",
"content-type: application/json",
"-d",
json.toString()};
ProcessBuilder pb = new ProcessBuilder(cmd);
Log.debug("COMANDO.TOSTRING " + pb.command().toString());
Process p = pb.start();
Log.debug(p.getOutputStream().toString());
p.waitFor();
BufferedReader reader
= new BufferedReader(new InputStreamReader(p.getInputStream()));
String readline;
while ((readline = reader.readLine()) != null) {
Log.debug(readline);
}
With the readline I have the server answer output but I don't know hot to get the curl command I have exectuted with the processbuilder.
EDIT 1:
I just need to send this command by using the linux console:
curl -X POST 'https://api.com/data/insert?access-token=Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD' -H 'content-type: application/json' -d '{ "pm25":2, "timestamp":1495077872, "dispositivo_mac": "12:34:56:78:90:12" }'
Basically I need to print the cmd array processed by the ProcessBuilder object to see it before the star method execution.
I had success with this code:
ProcessBuilder pb = new ProcessBuilder(command);
logger.debug(String.join(" ",pb.command().toArray(new String[0])));
Here is code for printing the runnable command:
private String getRunnableCommand(ProcessBuilder processBuilder)
{
List<String> commandsList = processBuilder.command();
StringBuilder runnableCommandBuilder = new StringBuilder();
int commandIndex = 0;
for (String command : commandsList)
{
if (command.contains(" "))
{
runnableCommandBuilder.append("\"");
}
runnableCommandBuilder.append(command);
if (command.contains(" "))
{
runnableCommandBuilder.append("\"");
}
if (commandIndex != commandsList.size() - 1)
{
runnableCommandBuilder.append(" ");
}
commandIndex++;
}
return runnableCommandBuilder.toString();
}
It will surround arguments containing spaces properly with quotation marks.

curl command in java

First of all , i've already seen couple of documents, stackoverflow questions regarding the same ..I've my project specific question
When trying to run command :
curl -u username:password https://example.com/xyz/abc
from the mac terminal , I get my desired json format data.
But running the same command from java code , I get Unauthorised 401 error in console.
My code is :
String username="myusername";
String password="mypassword";
String url="https://www.example.com/xyz/abc";
String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try
{
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.print(result);
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}
I get Unauthorised 401 error and bunch of html tags .
It seems like a repetitive question, but I've tried all the approaches.
I know alternative is using http response method, but particularly I want to use curl commands.
Thanks in advance.
Try changing this line
String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
into
String[] command = {"curl", "-H", "Accept:application/json", "-u", username+":"+password , url};
hey try this I had the same problem.
It worked in my terminal had the same error as yours.
String[] command = {"curl", "-u" , username+ ":" + password , url};

Categories

Resources