简体   繁体   中英

curl command execution in java

here is the curl command I'm trying to execute in java:

curl -XPOST \
   https://login.spredfast.com/v1/oauth/authorize \
   -d response_type="code" \
   -d state="<origState>" \
   --data-urlencode password="<userPassword>" \
   --data-urlencode client_id="<clientId>" \
   --data-urlencode email="<userEmail>" \
   --data-urlencode redirect_uri="<redirectUri>"

here is my java program of the above:

package jsontocsv;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class NoName2 {

  public static void main(String[] args) {
    NoName2 obj = new NoName2();



    String[] command = new String[]
            {
            "curl","-XPOST", "https://login.xyz.com/v1/oauth/authorize",

            "-d", "'response_type=code'",
            "-d", "'state=none'",
            "--data-urlencode","'password=<password>'",
            "--data-urlencode", "'client_id=<client id>'",
            "--data-urlencode", "'email=<email>'",
            "--data-urlencode", "'redirect_uri=https://localhost'",
            };

    String output = obj.executeCommand(command);
    System.out.println(output);
  }

  private String executeCommand(String...command) {
    StringBuffer output = new StringBuffer();

    Process p;
    try {
      p = Runtime.getRuntime().exec(command);

      //p.waitFor();
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          p.getInputStream()));
      System.out.println(reader.readLine()); // value is NULL
      String line = "";
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
        output.append(line + "\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return output.toString();
  }
}

But the output i get is not what I expect it to be. It appears that the highlighted lines of the curl command doesn't seem to be running:

"--data-urlencode","'password=<password>'",
"--data-urlencode", "'client_id=<client id>'",
"--data-urlencode", "'email=<email>'",
"--data-urlencode", "'redirect_uri=https://localhost'",

Is my code format of curl command and its parameters right?. Any help is much appreciated! Thanks in advance!

I would strongly encourage you to use a HTTP library for that and avoid executing external programs. There are bunch of HTTP libraries for Java out there ( Rest clients for Java? ).

You definately should have a look at Retrofit, which is pretty convenient in my opinion ( http://square.github.io/retrofit/ ).

You may also want to use OkHTTP or AsyncHTTPClient.

Example of the latter solving your problem:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
BoundRequestBuilder r = asyncHttpClient.preparePost("https://login.xyz.com/v1/oauth/authorize");
r.addParameter("password", "<value>");
r.addParameter("client_id", "<id>");
r.addParameter("email", "<email>");
r.addParameter("redirect_uri", "https://localhost");
Future<Response> f = r.execute();

Response r = f.get();

The response object then provides the status code or the HTTP body. ( https://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/Response.html )

Edit:

A bit strange is that you are posting, but saying curl to url encode you parameters, that is not usual when using a HTTP Post, maybe you can try:

curl -XPOST \
   https://login.spredfast.com/v1/oauth/authorize \
   -d response_type="code" \
   -d state="<origState>" \
   --data 'password="<userPassword>"' \
   --data 'client_id="<clientId>"' \
   --data 'email="<userEmail>"' \
   --data 'redirect_uri="<redirectUri>"'

Edit: Complete Example

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        AsyncHttpClient.BoundRequestBuilder r = asyncHttpClient.preparePost("https://httpbin.org/post");
        r.addFormParam("password", "<value>");
        r.addFormParam("client_id", "<id>");
        r.addFormParam("email", "<email>");
        r.addFormParam("redirect_uri", "https://localhost");
        Future<Response> f = r.execute();

        Response res = f.get();

        System.out.println(res.getStatusCode() + ": " + res.getStatusText());
        System.out.println(res.getResponseBody());
    }

}

Output:

200: OK
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "client_id": "<id>", 
    "email": "<email>", 
    "password": "<value>", 
    "redirect_uri": "https://localhost"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Content-Length": "94", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "AHC/1.0"
  }, 
  "json": null, 
  "origin": "??.??.??.??", 
  "url": "https://httpbin.org/post"
}

You can add the AsyncHTTPClient library with maven like this( http://search.maven.org/#artifactdetails%7Ccom.ning%7Casync-http-client%7C1.9.36%7Cjar ):

<dependency>
    <groupId>com.ning</groupId>
    <artifactId>async-http-client</artifactId>
    <version>1.9.36</version>
</dependency>

In general just have a look at the different HTTP client libraries for Java, and use the one you most like (I prefer Retrofit as already mentioned).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM