Run cURL with digest authentication in java


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

2 answers


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

// 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.'http://xxxxx', entity, 'application/json', new AsyncHttpResponseHandler() {

        public void onSuccess(String response) {
            // hacer algo

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

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