0

我想在我的 java 项目中集成 MailChimp API。当我使用 HttpURLConnection 类调用 Rest 调用时,它会响应 401 代码。

这是我的代码:

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();
4

3 回答 3

4

我会建议使用Apache Commons Codec包进行编码。它支持各种格式,例如 Base64 和 Hexadecimal。

早些时候我也面临同样的问题。我正在共享我在应用程序中用于验证 Mailchimp API v-3.0 的代码

//basic imports
import org.apache.commons.codec.binary.Base64;
.
.
.
 //URL to access and Mailchimp API key 
String url = "https://us9.api.mailchimp.com/3.0/lists/";
//mailchimp API key 
String apikey = xxxxxxxxxxxxxxxxxxxxxxxxxxx

// Authentication PART

String name = "Anything over here!";
String password = apikey;     //Mailchimp API key
String authString = name + ":" + password;

byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection)           urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

InputStream is1 = httpConnection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is1, "utf-8"));

String line = null;
while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
            }
br.close();

现在您可以根据需要使用 StringBuilder Object sb来解析输出

希望它能解决你的问题:)

于 2016-08-09T20:42:14.593 回答
0

HTTP 401 仅表示您无权发送此请求。

您可以将username设置为任何字符串(MailChimp 文档建议将anystring其用作用户名)并将您的API 密钥设置为 password

在 Postman 请求的情况下,您可以在Authorization选项卡下设置选择Basic Auth设置用户名和密码。下图显示相同。

在此处输入图像描述

有关在 MailChimp API 3.0 上向邮件列表添加/获取成员/从邮件列表添加/获取成员的更多信息,我发现这篇文章非常有用。

于 2020-05-17T07:06:51.597 回答
0

HTTP 401 响应代码表示“未授权”。

您没有正确设置或传递您的凭据。是否设置了来自客户端的证书?这是 HTTPS 客户端的示例

于 2016-06-14T12:49:13.267 回答