代码之家  ›  专栏  ›  技术社区  ›  grooble

用Java获取MailChimp响应

  •  0
  • grooble  · 技术社区  · 6 年前

    我想使用MailChimp api添加订阅服务器。首先,我想从其他的部分中得到一个消息,我试图从MailChimp api中得到一个响应。

    以下是目前为止的代码:

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

    enter image description here

    我如何得到回应?

    如果有人在看上面的代码,输出应该是:

    System.out.println("DoPost response: \n" + sb);  // not line
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   grooble    6 年前

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

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

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

    …它起作用了。