在Java中执行curl命令

时间:2016-03-17 12:06:48

标签: java curl parameters

这是我试图在java中执行的curl命令:

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

这是我上面的java程序:

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

但我得到的输出并不是我所期望的。似乎curl命令的突出显示的行似乎没有运行:

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

我的curl命令及其参数的代码格式是否正确?任何帮助深表感谢!提前谢谢!

1 个答案:

答案 0 :(得分:0)

我强烈建议你使用HTTP库,避免执行外部程序。那里有很多用于Java的HTTP库(Rest clients for Java?)。

你肯定应该看一下Retrofit,在我看来这很方便(http://square.github.io/retrofit/)。

您可能还想使用OkHTTP或AsyncHTTPClient。

后者解决问题的例子:

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

然后,响应对象提供状态代码或HTTP正文。 (https://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/Response.html

编辑:

有点奇怪的是你发帖,但是说curl to url会对你的参数进行编码,这在使用HTTP Post时是不常见的,也许你可以试试:

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

编辑:完成示例

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

}

输出:

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

您可以像这样添加AsyncHTTPClient库(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>

一般来说,只需查看Java的不同HTTP客户端库,并使用您最喜欢的那个(我更喜欢已经提到的Retrofit)。