I am making a request to a site, they are using JSON for exchanging data. Hence I made the following request but it is giving an error -The remote server returned an error: (400) Bad Request.
URL3 is a string
httpWebRequest = (HttpWebRequest)WebRequest.Create(URL3);
httpWebRequest.Method = "POST";
httpWebRequest.Host = "url";
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
httpWebRequest.KeepAlive = true;
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Referer = "url2";
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
httpWebRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
string postData = "";
postData += "{\"prefixText\":\"hyderabad\",\"count\":10,\"contextKey\":\"45\"}";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postData); //posting the data
requestWriter.Close();
**httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();**
responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseData_3 = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
Please help me.
Related
After new windows 10 update (1803) I have problem with sending data.
MESSAGE:
the underlying connection was closed an unexpected error occurred on a send
If anyone has any idea I would be very grateful
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
request.Method = "POST";
request.Headers.Clear();
request.AllowAutoRedirect = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
request.Timeout = 10000; //1 sec = 1000 ms
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] byteStream = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(potpisaniRacunString);
request.ContentLength = byteStream.LongLength;
request.ContentType = "text/xml";
using (Stream writer = request.GetRequestStream()) <--- BOOOM ! (The underlying connection was closed: An unexpected error occurred on a send.)
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
When I put the project to the server, get error - 500 internal server error. On local machine everything works fine. Can anybody help me? Here is my code:
`
string path = "xxx.p12";
string path2 = "xxx.crt";
X509Certificate2 certificate1 = new X509Certificate2(Server.MapPath("~/Files/" + path), "", X509KeyStorageFlags.MachineKeySet);
X509Certificate2 certificate2 = new X509Certificate2(Server.MapPath("~/Files/" + path2));
X509Certificate2Collection certificates = new X509Certificate2Collection();
certificates.Add(certificate1);
certificates.Add(certificate2);
X509Certificate2 certificate = certificates[0];
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "Post";
request.Timeout = 1000;
byte[] postBytes = Encoding.UTF8.GetBytes(post_data);
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
request.ContentLength = postBytes.Length;
request.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = null;
request.ClientCertificates.Add(certificate);
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
XmlDocument doc = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
}
`
When I ran my web application code I got this error on this line.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){}
Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception.
Here MyCode is :-
string service = "http://api.ean.com/ean-services/rs/hotel/";
string version = "v3/";
string method = "info/";
string hotelId1 = "188603";
int hotelId = Convert.ToInt32(hotelId1);
string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US¤cyCode=INR";
string apiKey = "tzyw4x2zspckjayrbjekb397";
string sig = "a6f828b696ae6a9f7c742b34538259b0";
string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = 0;
XmlDocument xmldoc = new XmlDocument();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata);
xmldoc.Save(#"D:\FlightSearch\myfile.xml");
xmldoc.Load(#"D:\FlightSearch\myfile.xml");
DataSet ds = new DataSet();
ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml");
GridView1.DataSource = ds.Tables["HotelSummary"];
GridView1.DataBind();
}
The error is providing all you need.
The method POST might not be supported by the api or for this call.
This should work. Try changing the method to "GET"
request.Method = "GET";
In Browser you are sending a GET request to the api. You should do the same in the code as well.
For XML Response:
request.Method = "GET";
request.ContentType = "text/xml; charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
request.Accept = "application/xml";
request.ContentLength = 0;
I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:
WebRequest req = WebRequest.Create("accounts.craigslist.org/login/pstrdr");
req.Method = "POST";
req.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
//WebRequest.Parameters.add("areaabb","hou");
obviously the commented line does not work. How do I achieve this?
Try like this...
string email = "YOUR EMAIL";
string password = "YOUR PASSWORD";
string URLAuth = "https://accounts.craigslist.org/login";
string postString = string.Format("inputEmailHandle={0}&name={1}&inputPassword={2}", email, password);
const string contentType = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.Expect100Continue = false;
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.CookieContainer = cookies;
webRequest.ContentLength = postString.Length;
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Referer = "https://accounts.craigslist.org";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
webRequest.GetResponse().Close();
Hi i'm getting encoding problems with the code below any ideas?
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
Response.Write(retVal);
}
My Screenshoot is like that;
Thanks for your help!
Google is notorious for checking the useragent HTTP header. Because you're not setting it its encoding everything as ISO-8859-9. The simple solution is to manually set the UserAgent property of the HttpWebRequest. Set it to anything you want, below is a Firefox string (and an extra Using block):
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string retVal = reader.ReadToEnd();
Console.WriteLine(retVal);
}
}