ADD Contact using c# getting error Bad Parameter (400)

Participant

ADD Contact using c# getting error Bad Parameter (400)

Error I am getting:

400Bad parameter 'activityType = '', valid values are: ((SV_ADD, SV_ADD_DTL, SV_RMV_INTERESTS, SV_EXPORT)).

Sample Code:

try
{
string sUserName = "USERNAME";
string sPassword = "PASSWORD";
string sUri = "http://api.constantcontact.com/ws/customers/" + sUserName + "/activities";
string sListUri = "http://api.constantcontact.com/ws/customers/" + sUserName + "/lists/4"; //I have 4 contact lists
string sAPIKey = "xxxxxxx-xxxx-xxxxx-xxxxxxxxx";

string address = new Uri(sUri).ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

request.Credentials = new NetworkCredential((sAPIKey + "%" + sUserName), sPassword);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

StringBuilder data = new StringBuilder();
data.Append("activityType=" + HttpUtility.UrlEncode("ADD_CONTACTS", Encoding.UTF8));
data.Append("&data=");
data.Append(HttpUtility.UrlEncode("Email Address,", Encoding.UTF8));
data.Append(HttpUtility.UrlEncode("First Name,", Encoding.UTF8));
data.Append(HttpUtility.UrlEncode("Last Name", Encoding.UTF8));
data.Append(HttpUtility.UrlEncode("\n", Encoding.UTF8));

data.Append(HttpUtility.UrlEncode("test@test.com,", Encoding.UTF8));
data.Append(HttpUtility.UrlEncode("FNAME,", Encoding.UTF8));
data.Append(HttpUtility.UrlEncode("LNAME", Encoding.UTF8));

data.Append("&lists=");
data.Append(HttpUtility.UrlEncode(sListUri, Encoding.UTF8));

byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

string st = string.Empty;

request.ContentLength = byteData.ToString().Length;
Stream postStream = request.GetRequestStream();
postStream.Write(byteData, 0, byteData.ToString().Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
catch (WebException ex)
{
st = (new StreamReader(ex.Response.GetResponseStream())).ReadToEnd();
}
1 REPLY 1
Moderator

The cause of the error is the postStream.Write command. Changing these lines:

request.ContentLength = byteData.ToString().Length;
Stream postStream = request.GetRequestStream();
postStream.Write(byteData, 0, byteData.ToString().Length);

To the following:

request.ContentLength = byteData.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(byteData, 0, byteData.Length);

Will result in a successful activity creation.
Dave Berard
Senior Product Manager, Constant Contact
Developer Portal

View API documentation, code samples, get your API key.

Visit Page