我想在不使用任何框架的情况下,使用基本认证调用 java
中的 GET
和 POST
API。请问有没有一些教程链接可以帮助我?在谷歌上,我只找到了关于 Spring
框架的代码,但是我不使用 Spring
。我正在寻找使用基本认证调用API的代码。
如果API已经被基本认证保护,并且它是一个 POST
方法,我需要在以下 代码
中添加具有 身份验证
的新 url
。考虑到我是一个新手,所以不太清楚需要做哪些修改。
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());
}
}
}
Accept
的头。以同样的方式添加Authentication
头。在这里查看:https://dev59.com/umcs5IYBdhLWcg3wk0-X - f1sh