【发布时间】:2018-12-25 13:12:56
【问题描述】:
我想使用 MailChimp api 添加订阅者。首先,想从我试图从 MailChimp api 获取响应的 REST 中读取。
当我获得状态 200 时,我似乎正确地进行了授权,但由于某种原因,我没有得到响应。
这是目前为止的代码:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
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 is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
看着 MailChimp 游乐场,我好像错过了很多……
如何获得响应?
****/ 编辑 /**** 如果有人在看上面的代码,输出应该是:
System.out.println("DoPost response: \n" + sb); // not line
【问题讨论】:
-
尝试逐行调试。使用正确的标题确保 URL 正确
-
@MaruthiAdithya 您好,感谢您的评论。我想知道你是否曾经用 Java 和 REST api 做过这个或类似的事情?如果是这样,你能给我一个关于 REST 服务的工作示例吗?
-
我已经多次这样做了,但不是使用 MailChimp,而是使用其他服务。在开始使用 Java 之前,尝试通过 Postman 或其他客户端获取响应以确保其正常工作