Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth with Unirest JAVA

I need to execute a request to a web app that execute a patch process. I'm giving to this request the parameters it is requesting me, but i do not know how to pass the credentials from a login request i'm executing before the patch request. I'm trying to get the cookie data from the headers of the login response and giving it to the patch request as a simple string, but i'm not sure if it is the right way to do it. Basically what i'm doing is this.

HttpResponse<JsonNode> respuesta = Unirest.post(urlLogin)
    .headers(headers)
    .fields(fields)
    .asJson();
JSONObject body = respuesta.getBody().getObject();
Headers headerBody = respuesta.getHeaders();
String tmp = headerBody.get("set-cookie").get(0);
this.cookie = "sd-touch-mode=false; ".concat(tmp.replace(";Path=/;HttpOnly",""));
Map<String,String> cabeceras = new HashMap<String, String>();
cabecera.put("Cookie", this.cookie);
HttpResponse<JsonNode> respuesta = Unirest.post(urlFixpack)
    .headers(headers)
    .fields(fields)
    .asJson();

I'm not comfortable with the way i'm getting and setting the cookie data, but i'm not finding in the documentation any proper way to do it.

can anybody help me please.

Thanks.

like image 881
JuanToroMarty Avatar asked Sep 15 '14 14:09

JuanToroMarty


1 Answers

Looks like not supporting cookies is a conscious design decision in Unirest. From the comments of a pull-request that adds cookie support:

A REST API should be stateless, so I would like to avoid cookies support in our mainstream client libraries.. but I will keep this pull request open, so if anyone has to access an API with cookies he'll be able to use your code ;)

But, without testing it, I'm under the impression that playing with custom HTTP clients should work. I'd give a try to something similar to this

cookieStore = new org.apache.http.impl.client.BasicCookieStore();
Unirest.setHttpClient(org.apache.http.impl.client.HttpClients.custom()
                            .setDefaultCookieStore(cookieStore)
                            .build());
like image 168
xverges Avatar answered Sep 28 '22 01:09

xverges