0

I have a requirement in my workplace, where I need to make a Get request from my Java code to a Rest API of a 3rd party application, to fetch some xml data.

I can access the Rest URL from my browser, where it asks for username and password. Once I enter the credentials, XML response is displayed on the browser.

But when I try to access the same API from Java 7 by passing username and password, I get a "401: Unauthorized" error.

I have provided the code that makes the GET request to the API.

public static void MyGetRequest()
{
 URL urlForGetRequest= new URL("http:myproject.dev.myclient/api/projects"); //sample URL
HttpURLConnection connection= (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("username","password"); //I pass my username and password here
int responseCode= connection.getResponseCode();
String responseMessage= connection.getResponseMessage();
System.out.println("HTTP Response Code:" +responseCode);
System.out.println("HTTP Response Message:" +responseMessage);

if(responseCode==HttpURLConnection.HTTP_OK)
{
 //code to fetch the XML response
}
}

Request you to help me by advising where I am going wrong. As this is my first ever task in making API calls, please ignore if this is a silly question.

Krishna
  • 21
  • 6
  • Does this answer your question? [Connecting to remote URL which requires authentication using Java](https://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java) – jannis Jan 08 '20 at 16:06
  • Assuming this is [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) you are missing the [Authorization HTTP header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization). – jannis Jan 08 '20 at 16:08

0 Answers0