【问题标题】:get MailChimp response with Java使用 Java 获取 MailChimp 响应
【发布时间】: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 或其他客户端获取响应以确保其正常工作

标签: java rest get mailchimp


【解决方案1】:

好的,上面的代码有效。基本错误。

当它为空时,我正在检查 line 变量,而不是响应...

当我更改为:

System.out.println("DoPost response: \n" + line);  // not line
System.out.println("DoPost response: \n" + sb);  // but sb StringBuilder

...它有效。

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 2020-05-08
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2015-12-03
    相关资源
    最近更新 更多