我想將MailChimp API集成到我的Java項目中。當我使用HttpURLConnection類調用Rest調用時,它使用401代碼進行響應。Java中的MailChimp集成
這裏是我的代碼:
URL url = new URL("https://us13.api.mailchimp.com/3.0/lists");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "apikey <my-key>");
String input = "<json data>";
OutputStream os = conn.getOutputStream();
//os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
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();
嗨,感謝您的及時答覆。是的,我知道問題在於傳遞api密鑰的方式。我檢查了MailChimp api,並且他們沒有任何關於如何在Java中傳遞api密鑰來授權的示例。 – user3759750
這是HTTP,所以我的第一個猜測是設置HTTP基本身份驗證標頭。 – duffymo
MailChimp API使用基本身份驗證。世界上有很多java的例子,比如[this](http://stackoverflow.com/questions/4883100/how-to-handle-http-authentication-using-httpurlconnection)。 – TooMuchPete