使用Java和Jersey客户端向Mailchimp受众添加新订户

时间:2019-06-12 16:59:46

标签: java post jersey-client mailchimp-api-v3.0

我需要将订阅者添加到mailchimp听众。我正在使用Java和Jersey客户端。我很容易使用Mailchimp 3.0 API来获取观众的成员。为了成功添加新订户,我的发帖请求必须更改什么?当我的代码失败时,没有响应。然后,当我检查Mailchimp帐户并看到没有添加新订户时。

class MailchimpClient {

    Client client;
    String mailchimpUrl;

    public MailchimpClient() {
        String mailchimpApikey = getAPIKey();
        String datacenter = mailchimpApikey.substring(mailchimpApikey.lastIndexOf('-') + 1);
        mailchimpUrl = "https://" + datacenter + ".api.mailchimp.com/3.0/";

        JacksonJsonProvider jjp = new JacksonJsonProvider();
        jjp.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ClientConfig conf = new ClientConfig();
        conf.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
        conf.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
        conf.register(jjp);

        HttpAuthenticationFeature httpAuth = HttpAuthenticationFeature.basic("username", mailchimpApikey);

        client = ClientBuilder.newClient(conf).register(httpAuth);
    }

    public <T> T get(String path, Class<T> responseType) {
        T t = client.target(mailchimpUrl).path(path).request(MediaType.APPLICATION_JSON).get(responseType);
        client.close();
        return t;
    }

    public <T> T post(String path, Object payload, Class<T> responseType) {
        Entity<Object> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
        T t = client.target(mailchimpUrl).path(path).request(MediaType.APPLICATION_JSON).post(entity, responseType);
        client.close();
        return t;
    }

    String audienceid = xxxxxxx;
    MailchimpClient mcc = new MailchimpClient();
    MembersResponse mr = mcc.get("lists/" + audienceid + "/members", MembersResponse.class);
    addToMailchimpAudience(String audienceid);

private Message addToMailchimpAudience(String audienceid) {
    HashMap<String, String> newMember = new HashMap<String, String>();
    newMember.put("email_address", "bob@gmail.com");
    newMember.put("status", "subscribed");
    MailchimpClient mcc = new MailchimpClient();
    MembersResponse mr = mcc.post("lists/" + audienceid + "/members", newMember, MembersResponse.class);
    logger.info("response: " + mr);
    return Message.success("Successfully added new member to mailchimp audience");

}


1 个答案:

答案 0 :(得分:0)

添加新成员的请求应为JSON 将联系人添加到列表/受众

要将联系人添加到列表/受众,请将POST请求发送到列表成员端点:/3.0/lists/9e67587f52/members/。请求正文应该是一个JSON对象,其中包含要添加的信息,状态和其他任何必需的列表字段。

{ “ email_address”:“ urist.mcvankab@freddiesjokes.com”, “ status”:“已订阅”, “ merge_fields”:{ “ FNAME”:“ Urist”, “ LNAME”:“ McVankab” } }

我观察到您正在在HasMap中发送值,尝试转换为JSON并查看其是否有效

链接供您参考: https://developer.mailchimp.com/documentation/mailchimp/guides/manage-subscribers-with-the-mailchimp-api/