首页 > 解决方案 > 使用不记名令牌在 java 中调用 GET API

问题描述

我需要为以下代码发送不记名令牌。下面的代码正在运行,但我必须使用受令牌保护的 GET 调用另一个休息端点。我需要在下面的代码中做些什么?我只想替换 url 并需要添加不记名令牌。

package com.shruti.getapi;

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(Proxy.NO_PROXY);
             //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());
        }
        
    }
}

标签: javarestweb-servicesgetbearer-token

解决方案


conn.setRequestProperty("Accept", "application/json");

您想要这个想法,但对于Authorization标头。

Authorization = credentials

RFC 6750包括对 OAuth2 Bearer Token 凭证的 ABNF 描述

 b64token    = 1*( ALPHA / DIGIT /
                   "-" / "." / "_" / "~" / "+" / "/" ) *"="
 credentials = "Bearer" 1*SP b64token

推荐阅读