The Community is hosting an End of Summer sweepstakes! Participants must complete tasks to earn tickets that will enter them with a chance to win a free year of Constant Contact and other great prizes!*
*No Purchase Necessary. For Official Rules, visit here. Constant Contact’s End of Summer 2020 Sweepstakes ends on October, 20, 2020 at 11:50 PM EST.

C# Implementation: The remote server returned an error: (400) Bad Request.

Highlighted
Occasional Participant

C# Implementation: The remote server returned an error: (400) Bad Request.

/***
* Load into Constant Contact
***/

string APIKey = "[REMOVED]";
string Username = "[REMOVED]";
string Password = "[REMOVED]";
				
CredentialCache ccLoginCredentials = new CredentialCache();
ccLoginCredentials.Add(new Uri("https://api.constantcontact.com/ws/customers/[USERNAME]"), "Basic", new NetworkCredential(APIKey + "%" + Username, Password));
				
WebRequest wRequest = WebRequest.Create("https://api.constantcontact.com/ws/customers/" + Username + "/contacts");
wRequest.Method = "POST";
wRequest.ContentType = "application/atom+xml";
wRequest.Credentials = ccLoginCredentials;


XmlWriterSettings xSettings = new XmlWriterSettings();
xSettings.Indent = true;
StringBuilder XMLData = new StringBuilder();
using (XmlWriter xWriter = XmlWriter.Create(XMLData, xSettings))
{

	xWriter.WriteStartDocument();
	xWriter.WriteStartElement("entry", "http://www.w3.org/2005/Atom");
	xWriter.WriteStartElement("title");
	xWriter.WriteStartAttribute("type");
	xWriter.WriteString("text");
	xWriter.WriteEndAttribute();
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("updated");
	xWriter.WriteString("2011-06-27T14:21:06.407Z");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("author");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("id");
	xWriter.WriteString("https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("summary");
	xWriter.WriteStartAttribute("type");
	xWriter.WriteString("text");
	xWriter.WriteEndAttribute();
	xWriter.WriteString("Contact");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("content");
	xWriter.WriteStartAttribute("type");
	xWriter.WriteString("application/vnd.ctct+xml");
	xWriter.WriteEndAttribute();
	xWriter.WriteStartElement("Contact", "https://ws.constantcontact.com/ns/1.0/");
	xWriter.WriteStartElement("EmailAddress");
	xWriter.WriteString("test@test.com");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("OptInSource");
	xWriter.WriteString("ACTION_BY_CUSTOMER");
	xWriter.WriteEndElement();
	xWriter.WriteStartElement("ContactLists");
	xWriter.WriteStartElement("ContactList");
	xWriter.WriteStartAttribute("id");xWriter.WriteString("https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]");
	xWriter.WriteEndAttribute();
	xWriter.WriteEndElement();
	xWriter.WriteEndElement();
	xWriter.WriteEndElement();
	xWriter.WriteEndElement();
	xWriter.WriteEndElement();
	xWriter.WriteEndDocument();

}

byte[] byteArray = Encoding.UTF8.GetBytes(XMLData.ToString());
try
{

	wRequest.ContentLength = byteArray.Length;
	Stream streamRequest = wRequest.GetRequestStream();
	streamRequest.Write(byteArray, 0, byteArray.Length);
	streamRequest.Close();
//Testing: Display Results
	HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
	StreamReader sReader = new StreamReader(wResponse.GetResponseStream());
	string xResponse = sReader.ReadToEnd();

	Response.Write(xResponse);

}
catch (WebException ex)
{

	Response.Write("WebException: " + ex.Status + " With response: " + ex.Message);

}

And here is the generated XML that I am attempting to POST

 

<?xml version="1.0" encoding="utf-16"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text" />
  <updated>2011-06-27T14:21:06.407Z</updated>
  <author />  <id>https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]</id>
  <summary type="text">Contact</summary>
  <content type="application/vnd.ctct+xml">
    <Contact xmlns="https://ws.constantcontact.com/ns/1.0/">
      <EmailAddress>test@test.com</EmailAddress>
      <OptInSource>ACTION_BY_CUSTOMER</OptInSource>
      <ContactLists>
        <ContactList id="https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]" />
      </ContactLists>
    </Contact>
  </content>
</entry>

 

 

Greetings. I am pretty new to the CC API and unfortunately I am also having an issue with my C# code returning a 400 (Bad Request) error. I am attempting to create a new contact.

 

I have verified that the authentication portion of the code above works as I used it to GET my list id values. I am assuming that this is some sort of issue with malformed XML or perhaps the way I am encoding the data for the POST but I'm just not sure. Perhaps I am using HTTPS where I should be using HTTP above as well.

 

 

Any help would be hugely appreciated.

 

Thanks in advance.

5 REPLIES 5
Highlighted
Employee

Re: C# Implementation: The remote server returned an error: (400) Bad Request.

Hello,

 

I believe that the problem you are having is that you are creating the XML with the UTF-16 encoding.  Our API servers require that the XML being submitted be UTF-8.

 

I took a look at that class and I believe you can change the UTF encoding by using:

 

settings.Encoding = Encoding.UTF8; 

 

If you have any issues, or are still running into the problem, please let me know.

 

Regards,

Benjamin Soder
NOC Analyst
Constant Contact
Highlighted
Occasional Participant

Re: C# Implementation: Now a (500) Internal Server Error

Benjamin, Thanks for the response. I tried 

 

settings.Encoding = Encoding.UTF8;

 

however apparently .NET ignores is as it treats strings as UTF-16 soooo.....

 

I've done some more reading about the encoding and modified my code as seen below and I am now getting a different error (500 - Internal Server Error). The XML should now be encoded as UTF-8 at least.

 

/***
* Load into Constant Contact
***/

string APIKey = "[API KEY]";
string Username = "[USERNAME]";
string Password = "[PASSWORD]";

CredentialCache ccLoginCredentials = new CredentialCache();
ccLoginCredentials.Add(new Uri("https://api.constantcontact.com/ws/customers/[USERNAME]"), "Basic", new NetworkCredential(APIKey + "%" + Username, Password));

WebRequest wRequest = WebRequest.Create("https://api.constantcontact.com/ws/customers/" + Username + "/contacts");
wRequest.Method = "POST";
wRequest.ContentType = "application/atom+xml";
wRequest.Credentials = ccLoginCredentials;

string XMLData;

MemoryStream mStream = new MemoryStream();
using (XmlTextWriter xWriter = new XmlTextWriter(mStream, Encoding.UTF8))
{

     xWriter.Indentation = 4;
     xWriter.IndentChar = ' ';
     xWriter.Formatting = Formatting.Indented;

     xWriter.WriteStartDocument();
     xWriter.WriteStartElement("entry", "http://www.w3.org/2005/Atom");
     xWriter.WriteStartElement("title");
     xWriter.WriteAttributeString("type", "text");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("updated");
     xWriter.WriteString("2011-06-27T14:21:06.407Z");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("author");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("id");
     xWriter.WriteString("https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("summary");
     xWriter.WriteAttributeString("type", "text");
     xWriter.WriteString("Contact");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("content");
     xWriter.WriteAttributeString("type", "application/vnd.ctct+xml");
     xWriter.WriteStartElement("Contact", "https://ws.constantcontact.com/ns/1.0/");
     xWriter.WriteStartElement("EmailAddress");
     xWriter.WriteString("test@test.com");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("OptInSource");
     xWriter.WriteString("ACTION_BY_CUSTOMER");
     xWriter.WriteEndElement();
     xWriter.WriteStartElement("ContactLists");
     xWriter.WriteStartElement("ContactList");
     xWriter.WriteAttributeString("id", "https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]");
     xWriter.WriteEndElement();
     xWriter.WriteEndElement();
     xWriter.WriteEndElement();
     xWriter.WriteEndElement();
     xWriter.WriteEndElement();
     xWriter.WriteEndDocument();

     xWriter.Flush();

     StreamReader bReader = new StreamReader(mStream, Encoding.UTF8, true);
     mStream.Seek(0, SeekOrigin.Begin);
     XMLData = bReader.ReadToEnd();

}

//Response.Write(XMLData);

byte[] byteArray = Encoding.UTF8.GetBytes(XMLData);
try
{

    wRequest.ContentLength = byteArray.Length;
    Stream streamRequest = wRequest.GetRequestStream();
    streamRequest.Write(byteArray, 0, byteArray.Length);
    streamRequest.Close();

    HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
    StreamReader sReader = new StreamReader(wResponse.GetResponseStream());
    string xResponse = sReader.ReadToEnd();

    Response.Write(xResponse);

}
catch (WebException ex)
{

    Response.Write("WebException: " + ex.Status + " With response: " + ex.Message);

}
catch (XmlException xmlex)
{
    Response.Write(xmlex.Message);
}
catch (Exception ex)
{
    Response.Write(ex.Message);
}

 

Basically rather than using a StringBuilder I opted to try a MemoryStream object which allowed me to get the desired encoding (UTF-8). Below is my XML request...

 

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
    <title type="text" />
    <updated>2011-06-27T14:21:06.407Z</updated>
    <author />
    <id>https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]</id>
    <summary type="text">Contact</summary>
    <content type="application/vnd.ctct+xml">
        <Contact xmlns="https://ws.constantcontact.com/ns/1.0/">
            <EmailAddress>test@test.com</EmailAddress>
            <OptInSource>ACTION_BY_CUSTOMER</OptInSource>
            <ContactLists>
                <ContactList id="https://api.constantcontact.com/ws/customers/[USERNAME]/lists/[LIST ID]" />
            </ContactLists>
        </Contact>
    </content>
</entry>

 

Any ideas why I would be getting a 500 error now?

 

Again, thanks so much for assisting.

Highlighted
Employee

Re: C# Implementation: Now a (500) Internal Server Error

Hello,

 

I see two additional issues that may resolve this.  The ID node and the Contact node.

 

The ID node must be:

 

<id>data:,none</id>

The contact node must have the attribute xmlns="http://ws.constantcontact.com/ns/1.0/", you currently have xmlns="https://ws.constantcontact.com/ns/1.0/" (with an https).

 

When I changed these two nodes I was able to post your XML to my account.

 

If you have any questions please let me know.

 

Regards,

Benjamin Soder
NOC Analyst
Constant Contact
Highlighted
Occasional Participant

Re: C# Implementation: Now a (500) Internal Server Error

Thanks Benjamin! That seemed to do the trick!

 

I really appreciate your help with this.

Highlighted
Employee

Re: C# Implementation: Now a (500) Internal Server Error

No problem!  If you run into any other issues please feel free to post in the forums!

 

Sincerely,

Benjamin Soder
NOC Analyst
Constant Contact
Developer Portal

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

Visit Page

Constant Contact 2020 End of Summer Community Sweepstakes!

The Constant Contact User Community is hosting a sweepstakes. The more you participate, the more chances you have to win! Read on to learn more...

Read More
Featured