0

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!

khalibali
  • 123
  • 1
  • 2
  • 16
  • 2
    Is there a reason you are calling curl from java? Did you know you can do everything curl can do from java, without starting another process? – weston Mar 17 '16 at 12:17

1 Answers1

0

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).

Community
  • 1
  • 1
Magnus
  • 390
  • 2
  • 12
  • Hi Magnus, could you please show an example program of the above using AsyncHTTPClient? I tried, but I'm getting a lot of exceptions. – khalibali Mar 18 '16 at 06:15
  • Thanks a lot Magnus! Just one doubt. When I try to execute your code, I get this error on addFormParam : "The method addFormParam(String, String) is undefined for the type AsyncHttpClient.BoundRequestBuilder". What should I do to fix this? – khalibali Mar 21 '16 at 06:42
  • I haven't added the AsyncHTTPClient library with maven. Instead, I've just added async-http-client-1.9.36.jar as an external jar to the java build path. Not sure if its the same as adding it with maven. If not, please tell me how to add the AsyncHTTPClient library with maven, since I'm new to this. Thanks a lot in advance! – khalibali Mar 22 '16 at 04:32
  • In general this does not matter for the result, but managing dependencies with maven is far more convenient. How to do that depends on your project structure, are you using a build tool like maven or ant, is it an Android project? Or are you just using an IDE like eclipse to build and run you project? Do you still have the 'addFormParam : "The method addFormParam(String, String) is undefined' error? – Magnus Mar 22 '16 at 15:00
  • Yes I still have that 'addFormParam : "The method addFormParam(String, String) is undefined' error. I'm just using an eclipse IDE to build and run my project. I expect JSON output. – khalibali Mar 24 '16 at 09:46
  • The error has been resolved now. But I'm getting an exception like this: Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at com.ning.http.client.AsyncHttpClient.(AsyncHttpClient.java:152) at jsontocsv.Curl3.main(Curl3.java:13) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ... ... ... – khalibali Mar 24 '16 at 09:50
  • Basically what I'm trying to achieve is to use the api and retrieve data. The first step is to authorize your user with the client Id and clientSecret via /authorize. Upon success, this will return encrypted values 1 and 2 required for /grant. Using values one and two, a code is obtained. This code is used for obtaining access token. Something called as OAuth2 is used for authentication. I'm able to obtain values one and two through a separate java program and I'm manually obtaining code from the browser. I'm now trying to obtain the token (in the JSON output) by the process you've told. – khalibali Mar 24 '16 at 11:21
  • Please let me know if I'm following the right protocol. I handled the exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory by adding the "slf4j-api-1.7.13.jar" to the build path. When I run, I'm getting this output: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. 500: Internal Server Error {"locale":"en_US","i18n":{}} – khalibali Mar 24 '16 at 11:25
  • 500: Internal Server Error {"locale":"en_US","i18n":{}} seems to be the reply from your server. Did you try to query httpbin like in my example, or a different service? – Magnus Mar 24 '16 at 11:55
  • No, I just used my url, "https://login.spredfast.com/v1/oauth/authorize" in the preparePost statement. How should I use httpbin? – khalibali Mar 28 '16 at 05:58
  • Hi Magnus. I tried using just "https://httpbin.org/post". I got the output you had got. But I need to use my "url, https://login.spredfast.com/v1/oauth/authorize" and pass those parameters to that url. How do I achieve that? Thanks in advance. – khalibali Mar 28 '16 at 06:16