Joe Bernstein
Joe Bernstein

Reputation: 163

HTTP request is not working, setting Authorization using setRequestProperty method

I am trying to make a get request in Java. However, when I run this code,

URL urlForGetRequest = new URL("my_url");   
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");

String username = "user";
String password = "pass";

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
System.out.println(basicAuth);

conection.setRequestProperty("Authorization", "Basic "+basicAuth);

int responseCode = conection.getResponseCode();

System.out.println(responseCode);

It always returns a 403. I can type the url into the address bar and it returns what I need it to. Similarly, the credentials are correct. Am I missing a setRequestProperty beyond Authorization?

Upvotes: 0

Views: 128

Answers (1)

Eugene Kortov
Eugene Kortov

Reputation: 453

I guess the urlForGetRequest for your site and url for login are different. When you open a site, it's one url, and when you click the login button, you request another url, that's should be your urlForGetRequest.

Just try to login by correct hardcoded url for a start. And use POST method. And then you can either hardcode this url in your code or parse HTML response with jsoup, selenium maybe. I didn't solve such problems honestly. If you can control the code of this site, you can integrate some other auth options (0Auth, tokens) I'm not savvy with that, maybe someone can help you with it, it's another topic

Upvotes: 1

Related Questions