3

I want to call GET and POST API in java without using any framework. I need to use basic authentication. Can anybody help me with some tutorial link. In google I found code only in spring framework, But I am not using Spring. I am looking for code to call API with basic authentication.

I have to add new url with authentication in the below code. What modification is required if API is secured with basic auth and it is POST method. I am new to java so not much aware.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class NetClientGet {

    public static void main(String[] args)  {
        
        try
        {
            System.out.println("Inside the main function");
             URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
             HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
             conn.setRequestMethod("GET");
             conn.setRequestProperty("Accept", "application/json");
             System.out.println("Output is: "+conn.getResponseCode());
             System.out.println("Output is: ");
             System.setProperty("http.proxyHost", null);
             //conn.setConnectTimeout(60000);
             if(conn.getResponseCode()!=200)
             {
                 System.out.println(conn.getResponseCode());
                 throw new RuntimeException("Failed : HTTP Error Code: "+conn.getResponseCode());
             }
             System.out.println("After the 2 call ");
             InputStreamReader in=new InputStreamReader(conn.getInputStream());
             BufferedReader br =new BufferedReader(in);
             String output;
             while((output=br.readLine())!=null)
             {
                 System.out.println(output);
             }
             conn.disconnect();
             
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        
    }
}
Shruti sharma
  • 199
  • 6
  • 21
  • 67
  • 2
    Have you tried anything yet? That authentication is just a header field in a HTTP request. – f1sh Jun 24 '20 at 21:44
  • I have added the code in question. I am able to consume API with no auth. But i dont know how to consume POST API accepting basic auth. I am not using spring. – Shruti sharma Jun 24 '20 at 21:51
  • 2
    You are already setting a header called `Accept`. Add the `Authentication` header the same way. Take a look here: https://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection – f1sh Jun 24 '20 at 21:54
  • Thank you @f1sh I will go through the same. – Shruti sharma Jun 24 '20 at 21:55

1 Answers1

4

Basic Authentication

See the RFC #2617 section 2: Basic Authentication Scheme

Add Authentication header into the request. Here's an example:

String username = "john";
String password = "pass";
// ...
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
// snippet begins
conn.setRequestProperty("Authorization",
  "Basic " + Base64.getEncoder().encodeToString(
    (username + ":" + password).getBytes()
  )
);
// snippet ends
System.out.println("Output is: "+conn.getResponseCode());

POST Method

See this answer for more information about using POST method with HttpURLConnection.

haba713
  • 2,465
  • 1
  • 24
  • 45