我第一次尝试使用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();
}
}
}
谁能告诉我做错了什么?
潇湘沐
相关分类