How to pass POST parameters to ASP.Net web request? - asp.net

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();

Related

Asp.net Mvc. Error during execution https request

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());
}
`

curl Request with ASP.NET

I have read some other posts on Stack but I can't get this to work. It works fine on my when I run the curl command in git on my windows machine but when I convert it to asp.net it's not working:
private void BeeBoleRequest()
{
string url = "https://mycompany.beebole-apps.com/api";
WebRequest myReq = WebRequest.Create(url);
string username = "e26f3a722f46996d77dd78c5dbe82f15298a6385";
string password = "x";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}
This is the BeeBole API. Its pretty straight fwd. http://beebole.com/api but I am getting a following 500 error when I run the above:
The remote server returned an error: (500) Internal Server Error.
The default HTTP method for WebRequest is GET. Try setting it to POST, as that's what the API is expecting
myReq.Method = "POST";
I assume you are posting something. As a test, I'm going to post the same data from their curl example.
string url = "https://YOUR_COMPANY_HERE.beebole-apps.com/api";
string data = "{\"service\":\"absence.list\", \"company_id\":3}";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";
string usernamePassword = "YOUR API TOKEN HERE" + ":" + "x";
UTF8Encoding enc = new UTF8Encoding();
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));
using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);

System.Net.WebException: The remote server returned an error: (405) Method Not Allowed .exception occurred during the execution of the web request

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&currencyCode=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;

bad request 400 - httpwebrequest to a site

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.

Web Request Encoding Problem

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);
}
}

Resources