Can anyone see why I would receive a 400 Bad Request:
I'm trying to upload multiple contacts
My file is setup properly Email, FirstName, LastName, CompanyName
PublicSharedSub UploadMultipleContacts(ByVal sSelectedList AsString)
'A SUCCESSFUL UPLOAD RETURNS A STATUS OF 201 FROM THE RESPONSE VARIABLE.
'Setup your variables
Dim ctu AsString = CTU()
Dim ctp AsString = CTP()
Dim sUri AsString = "https://api.constantcontact.com/ws/customers/" & ctu & "/activities"
' complete uri for list selected, including list id.
Dim sListUri AsString = sSelectedList
Dim sAPIKey AsString = "??????"
'yep, too lazy to add in an open file dialog. put directory of CSV here
'Dumps CSV into a string
Dim filename AsString = "UploadData.csv"
Dim fullpath AsString = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/Constant_Contact"), filename)
Dim CSVFile AsString = System.IO.File.ReadAllText(fullpath)
Try
'Setup an HttpWebRequest to send the data
Dim address AsNewUri(sUri)
Dim request AsHttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Credentials =
NewNetworkCredential((sAPIKey & "%" & ctu), ctp)
request.Method =
"POST"
request.ContentType =
"multipart/form-data"
'Build an encoded string of the data to pass to Constant Contact
Dim data AsNewStringBuilder()
data.Append(
"activityType=" + HttpUtility.UrlEncode("ADD_CONTACTS", Encoding.UTF8))
'Encodes raw string into URLEncoded format
data.Append(
"&file=" + HttpUtility.UrlEncode(CSVFile))
data.Append(
"&lists=" + HttpUtility.UrlEncode(sListUri))
'The "guts" of the code to execute the request and return a response
'The response (returned as 'strResponse') will be XML. You can parse this for status messages if you like, or just ignore it.
Dim byteData AsByte() = UTF8Encoding.UTF8.GetBytes(data.ToString())
Dim st AsString = String.Empty
request.ContentLength = byteData.Length
Using postStream AsStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
EndUsing
Using response AsHttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader AsNewStreamReader(response.GetResponseStream())
st = reader.ReadToEnd()
EndUsing
Catch ex AsException
HttpContext.Current.Response.Write(ex.Message)
EndTry
EndSub
It looks like you are attempting to use an application/x-www-form-urlencoded Request, but are using the content-type 'multipart/form-data'. If you make the following changes, your code seemed to work properly for me:
1. Change:
request.ContentType = "multipart/form-data";
to:
request.ContentType = "application/x-www-form-urlencoded";
2. Change:
data.Append("&file=" & HttpUtility.UrlEncode(CSVFile))
to:
data.Append("&data=" & HttpUtility.UrlEncode(CSVFile))
If you are still receiving 400 errors after that, then please send us a few lines of example data from your CSV so that we can see exactly what information you are using.
David J