0

I am trying to perform the same task in Java, but can't seem to figure out how to particularly set the cookies.

I know how to do this in python:

response = requests.get(app_url,cookies=cookies,allow_redirects=False)

How do I do the equivalent in Java?

Skeol
  • 37
  • 7

4 Answers4

1

Open a URLConnection(HttpURLConnection or HttpsURLConnection, set the cookie and connect.

HttpURLConnection con;
InputStream is;
try{
    con=((HttpURLConnection)new URL(app_url).openConnection());
    con.setRequestProperty("Cookie",cookie);
    is=con.openStream();
    //recv code
}finally{
    if(is!=null){try{is.close();}catch(IOException e){}}
    if(con!=null){try{con.close();}catch(IOException e){}
}
dan1st
  • 12,568
  • 8
  • 34
  • 67
  • Ah yes, this works. In addition, to "allow_redirects=False" in Java you should do the following: `con.setInstanceFollowRedirects(false);` (Unrelated to cookies, but since it was included as part of the parameters). – Skeol Dec 23 '19 at 17:31
  • I think it is set to false by default. – dan1st Dec 23 '19 at 17:33
0

The typical solution is using Apache HttpClient. If you need a less engineered and/or third-party library free solution, I'd suggest URLConnection or the new Java 11 HttpClient.

private final CloseableHttpClient client = HttpClients.createDefault();

...

public String get(String appUrl, String cookie) {
    HttpGet request = new HttpGet(appUrl);
    request.setHeader("Cookie", cookie);

    try (CloseableHttpResponse response = client.execute(request)) {
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    }
}
cbryant02
  • 583
  • 4
  • 16
0

Using Java11's HttpClient it could look like follows:

HttpResponse<String> response = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NEVER)
    .build()
    .send(
        HttpRequest.newBuilder(URI.create(url))
            .header("cookieName", "cookieValue")
            .GET()
            .build(),
        HttpResponse.BodyHandlers.ofString());
ldz
  • 2,217
  • 16
  • 21
-1

I assume you can reliably do the request. If not, this could help you.

How to get HTTP response code for a URL in Java?

To handle cookies, you may want to look at this

How to set Cookies at Http Get method using Java

Both implementations use the basic Java HttpURLConnection class.

Mauricio
  • 186
  • 1
  • 11