3

我想在GET不使用任何. 我需要使用基本身份验证。任何人都可以帮我提供一些教程链接。在谷歌中,我只在框架中找到了代码,但我没有使用. 我正在寻找调用 API 的代码POSTjavaframeworkspringSpringbasic authentication.

我必须在下面添加新url的。如果是安全的,需要什么修改是方法。我是新手,所以不太了解。authenticationcodeAPIbasic authPOSTjava

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

1 回答 1

3

基本认证

请参阅 RFC #2617 第 2 节:基本身份验证方案

Authentication在请求中添加标头。这是一个例子:

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 一起使用的更多信息,请参阅此答案。

于 2020-06-24T22:53:28.553 回答