cancel
Showing results for 
Search instead for 
Did you mean: 

403 error while trying to remove contact from list

Occasional Participant

403 error while trying to remove contact from list

Hey everyone, 

 

I am trying to add some code to remove a specific email, from a specific list. 

Here is the code I have

 

Public Shared Sub RemovePMConstantContact(name As String, email As String)
        Dim emailAddress As String() = New String() {email.Trim()}
        Try
            Dim sUsername As String = "CCusername"
            Dim sPassword As String = "CCpassword"
            Dim sAPIKey As String = "CCapiKey"

            Dim address As New Uri("https://api.constantcontact.com/v2/activities/removefromlists")
            Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
            'request.Credentials = New NetworkCredential((sAPIKey & "%" & sUsername), sPassword)
            request.Headers.Add("api_key", sAPIKey)
            request.Method = "POST"
            request.ContentType = "application/json"
            Dim data As New StringBuilder()
            data.Append("{'import_data':[{'email_addresses':['" + email + "']}],'lists':['(listIDtoRemoveThemFrom']}")
            Dim byteData As Byte() = UTF8Encoding.UTF8.GetBytes(data.ToString())
            Dim st As String = String.Empty
            request.ContentLength = byteData.Length
            Using postStream As Stream = request.GetRequestStream()
                postStream.Write(byteData, 0, byteData.Length)
            End Using
            Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
                Dim reader As New StreamReader(response.GetResponseStream())
                st = reader.ReadToEnd()
            End Using
        Catch ce As Exception
            SendError("Error in RemovePMConstantContact: " + ce.Message, ce.StackTrace, "")
        End Try
    End Sub

 

But I keep getting "The remote server returned an error: (403) Forbidden."

 

Any ideas?

 

Thanks!

9 REPLIES 9
Honored Contributor

Re: 403 error while trying to remove contact from list

Hello,

 

In this case the source of your difficulty is definitely that you're attempting to use Basic Authentication with the V2 API, which is not supported. In order to resolve this, you'll need to get an Access Token, which you can do with the credentials that you already have. In order to do that, navigate to https://constantcontact.mashery.com/io-docs.

 

Once you're there, just paste your API key into the marked box and click on Get Access Token. Next you'll click "I already have an account", and then log in using your CTCT credentials and grant access. At the end you will be given an Access Token that can be used in your code.

 

Once you have the token, you need an authorization header int he following format:

Authorization: Bearer ACCESS_TOKEN

 

If you have any problems, please let me know!

 

Sincerely,

Elijah G.
API Support Engineer
Occasional Participant

Re: 403 error while trying to remove contact from list

Thank you Elijah

 

I am still getting The remote server returned an error: (403) Forbidden.

 

Currently using:

 

Dim emailAddress As String() = New String() {email.Trim()}
        Try
            Dim sUsername As String = "CCuser"
            Dim sPassword As String = "CCpassword"
            Dim sAPIKey As String = "CCapi"
            Dim sToken As String = "CCtoken"

            Dim address As New Uri("https://api.constantcontact.com/v2/activities/removefromlists")
            Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
            request.Credentials = New NetworkCredential((sAPIKey & "%" & sUsername), sPassword) ' - I tried it with and without this line
            request.Headers.Add("api_key", sAPIKey)
            request.Headers.Add("Authorization", sAPIKey)
            request.Method = "POST"
            request.ContentType = "application/json"
            Dim data As New StringBuilder()
            data.Append("{'import_data':[{'email_addresses':['" + email + "']}],'lists':['CClistID']}")
            Dim byteData As Byte() = UTF8Encoding.UTF8.GetBytes(data.ToString())
            Dim st As String = String.Empty
            request.ContentLength = byteData.Length
            Using postStream As Stream = request.GetRequestStream()
                postStream.Write(byteData, 0, byteData.Length)
            End Using
            Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
                Dim reader As New StreamReader(response.GetResponseStream())
                st = reader.ReadToEnd()
            End Using
        Catch ce As Exception
            SendError("Error in RemovePMConstantContact: " + ce.Message, ce.StackTrace, "")
        End Try
Honored Contributor

Re: 403 error while trying to remove contact from list

Turns out there were two problems and I didn't spot the other one initially! The Access Token is defienitely one issue, but the other is that the API Key is not being included correctly. It is meant to be sent as a query parameter instead of as a header. So for example, your request URL should be:

"https://api.constantcontact.com/v2/activities/removefromlists?api_key="&sAPIKey

If you make this change, as well as commenting out the line with the basic auth credentials, you should see success.

 

As a side note, you can try to catch a System.Net.WebException, as that will contain a member named Response of type WebResponse. The WebResponse class contains the method GetResponseStream() that will let you capture an error message describing the failure. As a general rule our API returns descriptive errors for any 400 level responses, and those should help a great deal in troubleshooting any issues that may arise.

 

Sincerely,

Elijah G.
API Support Engineer
Occasional Participant

Re: 403 error while trying to remove contact from list

Thank you again Elija, 

 

However now I am getting "The remote server returned an error: (401) Unauthorized."

 

Dim address As New Uri("https://api.constantcontact.com/v2/activities/removefromlists?api_key=" + sAPIKey)
                Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
                request.Headers.Add("Authorization", sToken)
                request.Method = "POST"
                request.ContentType = "application/json"
                Dim data As New StringBuilder()
                data.Append("{'import_data':[{'email_addresses':['" + email + "']}],'lists':['" + CClist + "']}")
                Dim byteData As Byte() = UTF8Encoding.UTF8.GetBytes(data.ToString())
                Dim st As String = String.Empty
                request.ContentLength = byteData.Length
                Using postStream As Stream = request.GetRequestStream()
                    postStream.Write(byteData, 0, byteData.Length)
                End Using
                Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
                    Dim reader As New StreamReader(response.GetResponseStream())
                    st = reader.ReadToEnd()
                End Using

 

Also, when I change request.Headers.Add("Authorization", "(MyToken)") to request.Headers.Add("Authorization", "Bearer (MyToken)") as the documentation shows at https://developer.constantcontact.com/docs/bulk_activities_api/bulk-activities-removecontacts-multip...

 

I get The remote server returned an error: (400) Bad Request.

Occasional Participant

Re: 403 error while trying to remove contact from list

Any other ideas?

Honored Contributor

Re: 403 error while trying to remove contact from list

Hello,

 

My apologies for getting back to you a bit late on this!

 

With what you've seen so far, the 401 error was caused by including the basic auth (username/password), and the 400 error indicates that something in your payload is incorrect. From looking at your code it seems that the list ID may be the cause, but I would suggest implementing some code into your exception handler that will allow you to read the error response from the API, as it will tell you what is wrong.

 

Sincerely,

Elijah G.
API Support Engineer
Occasional Participant

Re: 403 error while trying to remove contact from list

Eligah, 

 

I reworked my code to better follow the example given on https://developer.constantcontact.com/docs/bulk_activities_api/bulk-activities-removecontacts-multip...

 

Here is my current code: 

Try
            Try
                Dim sAPIKey As String =(MyApiKey)
                Dim sToken As String = (MyToken)
              
                Dim filename As String = System.Guid.NewGuid.ToString
                Dim path As String = "C:\inetpub\......\" + filename + ".txt"
                Dim data As New StringBuilder()
                If File.Exists(path) Then
                    File.Delete(path)
                End If
                Using sw As StreamWriter = File.CreateText(path)
                    sw.WriteLine(email.Trim)
                End Using
                Dim address As New Uri("https://api.constantcontact.com/v2/activities/removefromlists?api_key=" + sAPIKey)
                Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
                request.Headers.Add("Authorization", "Bearer "+ sToken)
                request.Method = "POST"
                request.Accept = "application/json"
                request.ContentType = "multipart/form-data"
                data.Append("file_name " + path.Replace("C:\inetpub\.....\", ""))
                data.Append("lists (MyListID)")
                Using sr As StreamReader = File.OpenText(path)
                    Do While sr.Peek() >= 0
                        data.Append("data " + sr.ReadLine())
                    Loop
                End Using
                    Dim byteData As Byte() = UTF8Encoding.UTF8.GetBytes(data.ToString())
                    Dim st As String = String.Empty
                    request.ContentLength = byteData.Length
                    Using postStream As Stream = request.GetRequestStream()
                        postStream.Write(byteData, 0, byteData.Length)
                    End Using
                    Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
                        Dim reader As New StreamReader(response.GetResponseStream())
                        st = reader.ReadToEnd()
                    End Using
            Catch ex As WebException
                Dim resp As String = ""
                Try
                    resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
                Catch ex3 As Exception
                    resp = "none"
                End Try
                SendError("Error 3: " + ex.Message, ex.StackTrace, resp)
            End Try
        Catch ce As Exception
            SendError("Error 4: " + ce.Message, ce.StackTrace, "")
        End Try

I am getting the following error:

Error in RemoveCC 3: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse() at CCClass.RemoveCC(String name, String email)
org.apache.cxf.interceptor.Fault: Couldn't determine the boundary from the message!

 

Once I add bounderies,

request.Accept = "application/json"
                request.ContentType = "multipart/form-data; boundary='xx"
                data.Append("file_name " + path.Replace("C:\inetpub\......\", "") + " --xx")
                data.Append("lists " + CClist + " --xx")
                Using sr As StreamReader = File.OpenText(path)
                    Do While sr.Peek() >= 0
                        data.Append("data " + sr.ReadLine() + " --xx--")
                    Loop
                End Using

I get "Unexpected End while searching for first Mime Boundary"

 

 

Highlighted
Occasional Participant

Re: 403 error while trying to remove contact from list

Solved. 

 

With the help of this article: http://www.briangrinstead.com/blog/multipart-form-post-in-c#comment-1153

I rebuilt the webrequest using a GUID boundary

Honored Contributor

Re: 403 error while trying to remove contact from list

Hello,

 

As you found, the multi-part POST requires boundaries, and it's important to have reasonably long and unique boundaries to ensure that there is no chance of them occurring within the content that is being uploaded. If you run into any other issues while working with the API, please let me know!

 

Sincerely,

Elijah G.
API Support Engineer