簡體   English   中英

使用不記名令牌在 java 中調用 GET API

[英]Calling GET API in java using bearer token

我需要為以下代碼發送不記名令牌。 下面的代碼正在運行,但我必須使用受令牌保護的 GET 調用另一個 rest 端點。 我需要在下面的代碼中做些什么? 我只想替換 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());
        }
        
    }
}
conn.setRequestProperty("Accept", "application/json");

你想要這個想法,但對於授權header。

Authorization = credentials

RFC 6750包括對 OAuth2 Bearer Token 憑證的 ABNF 描述

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM