我试图从在线数据库服务Ragic获取一些JSON信息,并且需要在标头中使用API密钥查询URL。我尝试过几种不同的编码方法,但每次我都会找回一个空URL,这意味着标题中缺少API密钥或标题是错误的。我不确定问题是什么,代码编译,但只是简单地返回一个空的HTML" {}",这意味着没有收到任何JSON。
package main;
import java.io.*;
import java.net.*;
import org.apache.commons.codec.binary.Base64;
public class Example {
public static void main(String[] args) throws UnsupportedEncodingException, Exception {
String apiKey = "apikey";
try {
URL url = new URL("https://api.ragic.com/parcare/new-tab/1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
String basicAuth = "Basic " + new String(new Base64().encode(apiKey.getBytes()));
basicAuth = basicAuth.replaceAll("\n", "");
conn.addRequestProperty("Authorization", basicAuth);
conn.setRequestMethod("POST");
conn.connect();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RuntimeException allDownloadExceptions) {
allDownloadExceptions.printStackTrace();
}
}
}