Run cURL with digest authentication in java

2

I have a curl command in the following way:

curl -X POST 'https://xxxxxxxxxxxxx' --digest -u user:pass -H 'Content-Type: application/json' -H 'Accept: application/json' --data-binary $'{"from" : "xxxx", "msg" : "xxxxxx", "frag": null}'

I want to run it in Java but I do not know how to insert the digest authentication ... Any ideas?

    
asked by ev3 13.06.2016 в 18:57
source

2 answers

1

You could use AsyncHttpClient . I have not used it but seeing examples could do something like this:

// el json a enviar
JSONObject params = new JSONObject();
params.put("from", "xxxxx");
params.put("message", "xxxxx");
params.put("frag", "");

// configuración del Realm para la autenticación
Realm realm = new Realm.RealmBuilder()
               .setPrincipal(user)
               .setPassword(admin)
               .setUsePreemptiveAuth(true)
               .setScheme(AuthScheme.DIGEST)
               .build();

// establecemos el header
StringEntity entity = new StringEntity(jsonParams.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

// enviamos la petición pasándole la url, la entidad, el mime type y el handler para ella.
client.post('http://xxxxx', entity, 'application/json', new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String response) {
            // hacer algo
        }
    })).setRealm(realm).execute();

The advantage is that you can make a request without depending on cURL, you only add the library to your project and that's it.

    
answered by 13.06.2016 в 20:42
0

You are correctly enabling digest authentication, it seems to me that your question is more focused on how to execute the call:

You can do it using Runtime.getRuntime().exec(command)

String command = "curl -X POST 'https://xxxxxxxxxxxxx' --digest -u user:pass -H 'Content-Type: application/json' -H 'Accept: application/json' --data-binary $'{\"from\" : \"xxxx\", \"msg\" : \"xxxxxx\", \"frag\": null}'";

Process p = Runtime.getRuntime().exec(command);             
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
    output.append(line + "\n"); 
}
    
answered by 13.06.2016 в 21:45