I tried searching all over the web but did not find anything useful. I built a java program that sends a post request with specific parameters to a website, and the user writes his/her personal_number and authenticate using a third party app. I'm using HttpURLConnection
so I think it handles the redirecting. The problem is, I need to extract the cookie header from the GET request after the authentication before sending any other requests. How to do it in Java?
Example from my code:
public class JavaPostRequest {
private static HttpURLConnection con;
String url = "https://somewebsite.com/home/authentication";
public JavaPostRequest(long personal_number){
try {
URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection(); //Opens a http thread
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Sec-Ch-Ua", "\"(Not(A:Brand\";v=\"8\", \"Chromium\";v=\"98\"");
con.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
con.setRequestProperty("Sec-Ch-Ua-Mobile", "?0");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
con.setRequestProperty("Sec-Ch-Ua-Platform", "\"Windows\"");
con.setRequestProperty("Origin", "https://somewebsite.com");
con.setRequestProperty("Sec-Fetch-Site", "same-origin");
con.setRequestProperty("Sec-Fetch-Mode", "cors");
con.setRequestProperty("Sec-Fetch-Dest", "empty");
con.setRequestProperty("Referer", "https://somewebsite.com/home");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
con.setRequestProperty("Connection", "close");
String jsonInputString = "{\"personal_number\":\""+ personal_number + "\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
} catch (Exception e) {}
finally{
con.disconnect();
}
}
}