-1

i have curl command its work fine in cmd but i want to run it in java code.The main thing bout command is it is calling a "POST" API which require authenticaton too. i have used debugger too its not going in the loop to read the response

String[] command = {"curl",url, "-H" ,"Content-Type: application/x-www-form-urlencoded","-X", username+ "&" + password ,"insecure"};
        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="" ;
            while ( (line = reader.readLine()) != null) {
                builder.append(line);
                System.out.println(line);
                builder.append(System.getProperty("line.separator"));
            }
            String result = builder.toString();
            System.out.print(result);

        }

curl 'https://integration.sirionlabs.office:9443/nifi-api/access/token' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' --data 'username=username&password=password' --compressed --insecure

The expected result is the bearer token which I need

karthikdivi
  • 2,975
  • 3
  • 22
  • 42
  • 1
    i want to run this command in java code:curl 'https://integration.sirionlabs.office:9443/nifi-api/access/token' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' --data 'username=username&password=password' --compressed --insecure – MOHD MUGHEES Sep 19 '19 at 12:48
  • 2
    You are approaching the solution in the wrong direction, you should look for an HTTP client instead of running the command from Java. – karthikdivi Sep 19 '19 at 12:49
  • Possible duplicate of [How to use java.net.URLConnection to fire and handle HTTP requests](https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests) – Kris Sep 19 '19 at 12:49
  • 1
    for a couple of reasons, for example windows do not have curl so your code simply does not run on windows. And the code will be very hard to maintain – karthikdivi Sep 19 '19 at 13:56

2 Answers2

1

Unirest is among the most common Java HTTP Clients in the moment I am writing this answer.

Here's an example of the cURL command you have shown using Unirest in Java.

The code is a bit tricky because of the --insecure flag in cURL and this is one of the possible solutions to obtain a similar result in Unirest (source: https://github.com/Kong/unirest-java/issues/70):

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class UnirestCertificateIgnore {

    private static HttpClient unsafeHttpClient;

    static {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();

            unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
                    .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            e.printStackTrace();
        }
    }

    public static HttpClient getClient() {
        return unsafeHttpClient;
    }

    public static void main(String[] args) {

        try {
            HttpClient creepyClient = RestUnirestClient.getClient();
            Unirest.setHttpClient(creepyClient);

            HttpResponse<String> response = Unirest.get("https://integration.sirionlabs.office:9443/nifi-api/access/token")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("cache-control", "no-cache")
                .body("username=username&password=password")
                .asString();

        } catch (UnirestException e) {
            e.printStackTrace();
        }
    }
}
Pitto
  • 6,355
  • 1
  • 29
  • 40
  • 1
    What about emulating curl’s `--insecure` option? – VGR Sep 19 '19 at 13:50
  • @VGR --insecure will just ignore cURL certificate internal check. Please read here: https://stackoverflow.com/questions/8520147/curl-insecure-option – Pitto Sep 19 '19 at 13:53
  • Very good point, @VGR! I need to do some tests to provide a precise answer but I'd assume no. Let me see if I can find some self signed certificate and be able to certify / improve my answer accordingly. – Pitto Sep 19 '19 at 14:03
  • I hope this solution can be better, @VGR Thanks for your time and teaching. – Pitto Sep 19 '19 at 14:12
0

Instead of running an external curl process, use Java to submit your request. This will work even on systems where curl isn’t installed, making your code truly multi-platform:

String body = String.format("username=%s&password=%s",
    URLEncoder.encode(username, StandardCharsets.UTF_8),
    URLEncoder.encode(password, StandardCharsets.UTF_8));

HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url));
// -H
builder.setHeader("Content-Type",
    "application/x-www-form-urlencoded; charset=UTF-8");
// --data
builder.POST(HttpRequest.BodyPublishers.ofString(body));
HttpRequest request = builder.build();

// --insecure
TrustManager acceptAll = new X509TrustManager() {
    @Override
    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType)
    throws CertificateException {
        // Deliberately empty.
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType)
    throws CertificateException {
        // Deliberately empty.
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
};
SSLContext context;
try {
    context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { acceptAll }, null);
} catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
}

HttpClient client = HttpClient.newBuilder().sslContext(context).build();
HttpResponse<String> response =
    client.send(request, HttpResponse.BodyHandlers.ofString());

int status = response.statusCode();
if (status >= 400) {
    throw new IOException("Request failed with code " + status);
}

String result = response.body();

The HttpRequest, HttpResponse, and HttpClient classes are from the java.net.http package.

VGR
  • 33,718
  • 4
  • 37
  • 50