Thursday, April 24, 2014

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

In one of the projects that I was working on I started getting this error as soon as the site was hosted on the test server.
To give a brief background on the requirement, I had a site that was making a HttpWebRequest to the home page of another site to get the cookies.These cookies were then reused in subsequent requests.The sample code which was working on my dev machine is below

HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(new Uri(sSiteHomeUrl));
oRequest.Method = "GET";
oRequest.ContentType = @"application/x-www-form-urlencoded";
oRequest.CookieContainer = oCookies;
oRequest.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
oRequest.UserAgent = @"CHROME browser version: 33.0 user agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36";
oRequest.Headers["Accept-Encoding"] = @"gzip,deflate,sdch";
oRequest.Headers["Accept-Language"] = @"en-US,en;q=0.8,de;q=0.6,es;q=0.4";

string sResponseData = string.Empty;          
using(WebResponse oWebResponse = oRequest.GetResponse())
using (Stream data = oWebResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(data))
{
      sResponseData = reader.ReadToEnd();
}

Once I tested it on my dev machine I moved the code and hosted the application on the test server.However on the test server I started getting this error.After a day of struggling and going through various forums I was able to fix the issue.

The problem was that both my site that was making a call to another site were on the same server under the same IIS. When creating the URL I was using the server name in the url.By replacing the servername with the Ip address I was able to successfully make the request from my site and get the cookies for subsequent requests.

Old call
http://servername:12348/Home.aspx

New call
http://ipaddressofserver:12348/Home.aspx

No comments: