-
Notifications
You must be signed in to change notification settings - Fork 0
/
CookieHandler.java
60 lines (48 loc) · 2.07 KB
/
CookieHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 11. Write a simple program for implementation of cookiepolicy
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URL;
public class CookieHandler {
public static void main(String[] args) {
try {
// Set the default CookieManager with a custom CookiePolicy
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
java.net.CookieHandler.setDefault(cookieManager);
// Create a URL object
URL url = new URL("http://www.google.com");
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method to GET
connection.setRequestMethod("GET");
// Get the response code
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print the response
//System.out.println("Response: " + response.toString());
System.out.println("URL: ww.google.com");
// Print the cookies stored in the CookieManager
System.out.println("Cookies:");
cookieManager.getCookieStore().getCookies().forEach(cookie -> {
System.out.println(cookie);
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setDefault(CookieManager cookieManager) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'setDefault'");
}
}