2016-01-26 61 views
4

連接到新的MailChimp 3.0 API(2.0正常工作)時出現問題。與MailChimp v3.0的連接API

我想寄一些訂戶。我究竟做錯了什麼?我可能試圖以錯誤的方式發送apikey(HTTP基本身份驗證)。文檔在這裏,但我無法使其工作:http://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://us12.api.mailchimp.com/3.0/lists/<listnumber>/members/"); 

string json = @" 
    { 
     ""email_address"": ""[email protected]"", 
     ""status"": ""subscribed"", 
     ""merge_fields"": { 
        ""FNAME"": ""Urist"", 
      ""LNAME"": ""McVankab"" 
     } 
    } 
"; 

byte[] data = Encoding.UTF8.GetBytes(json); 

request.Method = "POST"; 
request.Headers.Add("user", "<mykeynumber>"); 
request.ContentType = "application/json"; 
request.ContentLength = data.Length; 

using (System.IO.Stream stream = request.GetRequestStream()) 
{ 
    stream.Write(data, 0, data.Length); 
} 
+0

你看到了什麼樣的錯誤? – Mateo

回答

1

主要問題似乎是驗證。這是一個很好的答案,demonstrates HTTP Basic Auth with HTTPWebRequest

+1

非常感謝你,鏈接幫助。所以標題應該是: request.Headers.Add(「Authorization」,「Basic」+ apikey); –

+0

很高興幫助。請注意,[HTTP基本身份驗證](https://en.wikipedia.org/wiki/Basic_access_authentication)要求「basic」之後的部分爲Base64編碼的字符串,如果這是您要做的。 – TooMuchPete

0

任何其他人都來到這裏,我一直在玩,我認爲現在最好使用ASP.NET Web API庫來調用它。我這下面這個例子的工作:https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

,並從這個問題的答案一起合併它:Calling MailChimp API v3.0 with .Net

的例子使用了一個簡單的Windows控制檯應用程序,但可以移植到網絡:

// New code: 
    static HttpClient client = new HttpClient(); 

    static void Main() 
    { 
     RunAsync().Wait(); 
    } 

    static async Task RunAsync() 
    { 
     // New code: 
     client.BaseAddress = new Uri("https://us5.api.mailchimp.com/3.0/"); 

     client.DefaultRequestHeaders.Accept.Clear(); 

     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "<YOUR_API_KEY_HERE>"); 

     try { 

      HttpResponseMessage response = await client.GetAsync(""); 

      if (response.IsSuccessStatusCode) { 

       var results = await response.Content.ReadAsStringAsync(); 

       Console.WriteLine($"results (HTTP Status = {results})"); 
      } 
      else { 

       Console.WriteLine($"ERROR (HTTP Status = {response.StatusCode}"); 
      } 


     } 
     catch (Exception e) { 
      Console.WriteLine(e.Message); 
     } 

     Console.ReadLine(); 
    }