我第一次嘗試使用GET從REST API獲取數據。我可以使用郵遞員獲取數據,我只需通過GET屬性傳遞我的url,然后在Headers選項卡中傳遞兩個鍵值對,如下所示,并能夠以csv格式獲取數據記錄明智的數據(常規csv類型的輸出,列名有記錄)Headers tab in Postman autd_id:ddhd45t-78d0-54ad-8320-94aejit526 aith:token:hf2h1-d1a1-6589-c55d-94aejit526現在,我嘗試使用Java自己執行此操作,但收到錯誤代碼401。這意味著我猜錯了憑據,但這是正確的。這是我的代碼。import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;public class Brigade { public static void Getbrigadedata() { try { URL url = new URL( "https://Brigade.co-buying.com/api/reports/referred/brigade_raf1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String userCredentials = "ddhd45t-78d0-54ad-8320-94aejit526:9658hf2h1-d1a1-6589-c55d-94aejit526"; new Base64(); String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes())); conn.setRequestProperty("Authorization", basicAuth); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}誰能告訴我做錯了什么?
1 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
據我了解,基于您要使用的API所提供的信息,您將基于上述兩個標頭(及其值)的存在使用一種身份驗證機制。
通過郵遞員執行呼叫時,可以在工具的標題選項卡中設置這些標題。問題是盡管在您的代碼中,您從未這樣做。相反,您嘗試創建一個包含憑據的base64編碼值的字符串。
再次假設該API需要將標頭放置在適當的位置,我建議您嘗試將其設置為您所請求的標頭,然后嘗試執行該調用。從這種意義上講,您的代碼應類似于:
conn.setRequestProperty("<header_1>", "<header_value1>"); conn.setRequestProperty("<header_2>", "<header_value2>");
這樣做對您來說還不錯-再次考慮到API的身份驗證機制是基于您提到的標頭。
添加回答
舉報
0/150
提交
取消