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.