esecuzione del comando curl in java


Ecco il comando curl che sto cercando di eseguire 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>"

Ecco il mio programma java di cui sopra:

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();
  }
}

Ma l'output che ottengo non è quello che mi aspetto che sia. Sembra che le linee evidenziate del comando curl non sembrano essere in esecuzione:

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

Il mio formato di codice del comando curl e i suoi parametri sono corretti?. Qualsiasi aiuto è molto apprezzato! Grazie in anticipo!

Author: khalibali, 2016-03-17

1 answers

Ti incoraggio vivamente a utilizzare una libreria HTTP per questo ed evitare di eseguire programmi esterni. Ci sono un sacco di librerie HTTP per Java là fuori (Client Rest per Java?).

Sicuramente dovresti dare un'occhiata al Retrofit, che è piuttosto conveniente a mio parere (http://square.github.io/retrofit/).

Potresti anche voler usare OkHTTP o AsyncHTTPClient.

Esempio di quest'ultimo che risolve il tuo problema:

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();

La risposta object fornisce quindi il codice di stato o il corpo HTTP. (https://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/Response.html)

Modifica:

Un po ' strano è che stai postando, ma dicendo curl all'url codifica i tuoi parametri, che non è normale quando usi un post HTTP, forse puoi provare:

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>"'

Modifica: Esempio completo

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());
    }

}

Uscita:

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"
}

È possibile aggiungere la libreria AsyncHTTPClient con maven come 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 generale basta dare un'occhiata alle diverse librerie client HTTP per Java e usare quella che ti piace di più (preferisco il Retrofit come già accennato).

 0
Author: Magnus, 2017-05-23 11:45:08