使用基本身份验证获取并 Post API 调用 java

Get and Post API call in java with basic authentication

我想在 java 中调用 GETPOST API,而不使用任何 framework。我需要使用基本身份验证。任何人都可以帮我一些教程 link。在 google 中,我只在 spring 框架中找到代码,但我没有使用 Spring。我正在寻找使用 basic authentication.

调用 API 的代码

我必须在下面 code 中添加新的 urlauthentication。如果APIbasic auth保护,并且是POST方法,需要做哪些修改。我是 java 的新手,所以不太了解。

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());
        }
        
    }
}

基本身份验证

参见 RFC #2617 第 2 节:Basic Authentication Scheme

Authentication header 添加到请求中。这是一个例子:

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 方法

有关将 POST 方法与 HttpURLConnection 结合使用的详细信息,请参阅 this answer