Getting Data from webApi with HttpWebResponse in C# - c#

I'm trying to get a data from a web app on http://apps.theocc.com/encore2/home.do
This is a risk calculator and I have to send some data to it and get back response via C# HttpWebRequest. I started a session and restored cookies. Now I'm trying to post a Data to it, but I don't receive any response. Here is my code
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://apps.theocc.com/encore2/home.do");
httpWebRequest.Method = "GET";
httpWebRequest.KeepAlive = true;
var cookieContainer = new CookieContainer();
httpWebRequest.CookieContainer = cookieContainer;
WebHeaderCollection headerCollection = new WebHeaderCollection();
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
/* save headers */
for (int i = 0; i < response.Headers.Count; i++)
{
headerCollection.Add(response.Headers.AllKeys[i], response.Headers.Get(i));
}
/* save cookies */
foreach (Cookie cookie in response.Cookies)
{
cookieContainer.Add(cookie);
}
}
httpWebRequest = (HttpWebRequest)WebRequest.Create("http://apps.theocc.com/pmc/pmcdUploadFile.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
//Just restoring header and setting back cookies
util.RestoreSession(ref httpWebRequest,cookieContainer,headerCollection);
var sb = new StringBuilder();
var boundary = "----WebKitFormBoundaryKWYPlRmSNoLdzrb7";
sb.AppendFormat(boundary);
sb.AppendFormat("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"positionFile\"; filename=\"positions.csv\"");
sb.AppendFormat("\r\n");
sb.AppendFormat("Content-Type: application/vnd.ms-excel");
sb.AppendFormat("\r\n");
sb.AppendFormat("\r\n");
sb.AppendFormat("Media Type: application/vnd.ms-excel");
sb.AppendFormat("\r\n");
sb.AppendFormat(boundary);
sb.AppendFormat("\r\n");
sb.AppendFormat("form-data: form-data; name=\"refresh\"");
sb.AppendFormat("\r\n");
sb.AppendFormat("\r\n");
using (FileStream fs = new FileStream(#"C:\Users\....\positions.csv", FileMode.Open, FileAccess.Read))
{
byte[] contents = new byte[fs.Length];
fs.Read(contents, 0, contents.Length);
sb.Append(Encoding.Default.GetString(contents));
}
sb.AppendFormat("\r\n");
sb.AppendFormat(boundary);
sb.AppendFormat("\r\n");
byte[] fulldata = Encoding.Default.GetBytes(sb.ToString());
httpWebRequest.ContentLength = fulldata.Length;
using (Stream sw = httpWebRequest.GetRequestStream())
{
sw.Write(fulldata, 0, fulldata.Length);
}
var resp = (HttpWebResponse)httpWebRequest.GetResponse();
The format of the file I'm posting have to be ok, because this is the file I've got from the same web app in a manual way.
The session restoring method is as simple as this
public static void RestoreSession(HttpWebRequest webRqst, CookieContainer cc, WebHeaderCollection hc)
{
/* restore Session ID */
for (int i = 0; i < hc.Count; i++)
{
string key = hc.GetKey(i);
if (key == "Set-Cookie")
{
key = "Cookie";
}
else
{
continue;
}
string value = hc.Get(i);
webRqst.Headers.Add(key, value);
}
/* restore Cookies */
webRqst.CookieContainer = cc;
}
What am I doing wrong here?
Any suggestions would be helpful.

Related

Not receiving cookie suddenly for HttpWebRequest POST placed through Visual Studio C# code

There is a common framework in our company where we pass username, password, url and get the cookie back. It was working for me for a long time and suddenly it stopped working. My team mates are able to get the cookie successfully with no issues. Here is the common function that we use to get the cookie back. Please help me to complete the troubleshooting
public static CookieContainer GetAvidAuthCookies(string url, string userName, string password, bool allowAutoRedirect = false)
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
CookieContainer cookieContainer = new CookieContainer();
req = (HttpWebRequest) WebRequest.Create(url);
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.ContentType = "text/xml;charset=UTF-8"; //for SOAP
req.Timeout = 30000;
req.AllowAutoRedirect = allowAutoRedirect;
req.AllowWriteStreamBuffering = true;
req.Referer = url;
//req.Host = "api.avidxchange.net";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(userName + ":" + password));
var request = Common.GetMemoryStream("username=" + userName + "&password=" + password + "&submit=");
if (request != null)
{
req.ContentLength = request.Length;
Stream sw = req.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
request.Position = 0;
while ((bytesRead = request.Read(buffer, 0, buffer.Length)) != 0)
{
sw.Write(buffer, 0, bytesRead);
}
request.Flush();
request.Close();
sw.Flush();
sw.Close();
}
try
{
resp = (HttpWebResponse) req.GetResponse();
}
catch (WebException we)
{
resp = (HttpWebResponse) we.Response;
Debug.WriteLine("Response:" + we.InnerException + "\r\n" + resp.StatusCode + ":" +
new StreamReader(we.Response.GetResponseStream()).ReadToEnd());
var responseStream = we.Response.GetResponseStream();
if (responseStream != null) responseStream.Position = 0;
}
var rStream = resp.GetResponseStream();
var responseText = new StreamReader(rStream).ReadToEnd();
var t = resp.Cookies;
return cookieContainer;
}

multiple post requests same session c#

I'm coding a script that goes on a website, adds to cart an item, and checkout.
I manage to add to cart but when I want to checkout it's like nothing is in the cart.
How can I add to cart/ checkout using the same session?
Here is my code:
var request = (HttpWebRequest)WebRequest.Create(url_add_to_cart);
var postData = "utf8=✓";
postData += "style=" + data_style_id;
postData += "size=" + size;
postData += "commit=add to basket";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//checkout----------------
var url_checkout = link_general + "/checkout.json";
var request2 = (HttpWebRequest)WebRequest.Create(url_checkout);
var postData2 = "utf8=✓";
postData2 += "order[billing_name]=toto";
postData2 += "order[email]=toto#gmail.com";
var data2 = Encoding.ASCII.GetBytes(postData2);
request2.Method = "POST";
request2.ContentType = "application/x-www-form-urlencoded";
request2.ContentLength = data2.Length;
using (var stream2 = request2.GetRequestStream())
{
stream2.Write(data2, 0, data2.Length);
}
var response2 = (HttpWebResponse)request2.GetResponse();
var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString2);
When I do the checkout request it doesn't work and get the source corde of the website html home page
Thank you very much for your answers
You need to store request.CookieContainer in local variable and every time you need to send new request set it again
private CookieContainer cookieContainer;
private void SendRequest()
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
if (this.cookieContainer != null)
request.CookieContainer = this.cookieContainer;
else
request.CookieContainer = new CookieContainer();
...
...
...
this.cookieContainer = request.CookieContainer;
}
And add & to end of postData lines

How to call restful service with args in asp.net web form?

I want to use from Restful service in asp.net webform and C#. So I used HttpWebRequest and I could got Token successfully. But I can't call Restful service with parameter. Using this code I tried to send BrokerId as a parameter but I think this is wrong because that service show error authorization:
private void RemainInq(string Auth)
{
string Address = #"http://10.19.252.21:5003/Rest/Topup/RemainCreditInquiry";
Uri UriAddress = new Uri(Address);
var PostParam = "BrokerId=13000303";
var data = Encoding.ASCII.GetBytes(PostParam);
HttpWebRequest req = WebRequest.Create(UriAddress) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
req.Accept = "gzip,deflate";
req.ContentLength = data.Length;
req.Host = "10.19.252.21:5003";
req.Headers.Add("Authorization", Auth);
req.ContentLength = data.Length;
using (var strem = req.GetRequestStream())
{
strem.Write(data, 0, data.Length);
}
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd();
string[] s = Response.Split(',');
for (int i = 0; i < s.Count(); ++i)
s[i] = s[i].Substring(s[i].IndexOf(":") + 2, s[i].LastIndexOf('"') -
s[i].IndexOf(":") - 2);
loResponseStream.Close();
resp.Close();
}
Finally I could find answer.
private string[] CallSaleProvider(string YourParam1,string YourParam2)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://YourAddress");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", Auth);
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
YourParam=Value, YourParam=value,YourParam=value
});
streamWriter.Write(json);
}
string result;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
string[] s = result.Split(',');
for (int i = 0; i < s.Count(); ++i)
s[i] = s[i].Substring(s[i].IndexOf(":") + 2, s[i].LastIndexOf('"') - s[i].IndexOf(":") - 2);
httpResponse.Close();
return s;
}

Rest Client Authorization error

I want to call a rest client with basic authorization. I tried this but got a Unauthorized(401) exception in c# :
HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://someurl.com");
client.Method = "POST";
client.UseDefaultCredentials = true;
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(mailinglist.ToString());
client.ContentLength = bytes.Length;
using (var writeStream = client.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
client.ContentType = "application/json";
NetworkCredential nc = new NetworkCredential("8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//string credentials = String.Format("{0}:{1}", "8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//byte[] bts = Encoding.ASCII.GetBytes(credentials);
//string base64 = Convert.ToBase64String(bts);
client.PreAuthenticate = true;
//string authorization = String.Concat("Basic ", base64);
//Utils.WriteLog("Addaudience", authorization);
//client.Headers.Add(HttpRequestHeader.Authorization, authorization);
client.Credentials = nc;
client.Accept = "application/json";
using (var response = (HttpWebResponse)client.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
Please help me and tell me what is my mistake? I also tried to put Authorization string in the headers but not working.
Thanks.

WPF(C#) how to use a post request to transfer file?

I have a picture that is presented in the form of a byte array. I need to save it to a file and send a post request. Tell me how to do it better
Here is what I do
private Stream file;
public void Fun1()
{
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
file.Write(bt, 0, bt.Length);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http:// Mysite.com/image.php?image=FILE",file));
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
}
postStream.Close();
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
}
}
As a result, the server did not come, tell me what am I doing wrong
thanks for your reply.
But I have another problem. My picture is encoded in a string, the string I write to the stream and try to send to the server. In response comes everything is OK, but the type of request is "Get"(variable respons, method ReadCallbackSavePlayersfun1). Please tell me what's wrong
public void Fun1()
{
string str = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAA";
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
StreamWriter w = new StreamWriter(file,Encoding.UTF8);
w.WriteLine(str);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http://Mysite.com/image.php"));
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
w.Close();
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
var sbHeader = new StringBuilder();
if (file != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "picture", file);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", request.ContentType);
}
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (file != null ? file.Length : 0) + footer.Length;
postStream.Write(header, 0, header.Length);
if (file != null)
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
br.Close();
}
postStream.Write(footer, 0, footer.Length);
postStream.Flush();
postStream.Close();
}
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
try
{
String doc = "";
using (Stream streamResponse = response.GetResponseStream())
{
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(streamResponse, encode);
Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
doc += str;
count = readStream.Read(read, 0, 256);
}
}
}
catch
{ }
}
}
Posting web byte[] data in .Net is not that simple. Saving a byte[] to storage is easy, so I wont have code for that, but here is the method I use to post binary data.
This is originally from http://skysanders.net/subtext/archive/2010/04/12/c-file-upload-with-form-fields-cookies-and-headers.aspx with my modifications to suit
And to get the FileInfo, simply pass in
new FileInfo(fullPath)
Good luck : )
/// <summary>
/// Create a new HttpWebRequest with the default properties for HTTP POSTS
/// </summary>
/// <param name="url">The URL to be posted to</param>
/// <param name="referer">The refer</param>
/// <param name="cookies">CookieContainer that should be used in this request</param>
/// <param name="postData">The post data</param>
private string CreateHttpWebUploadRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData, FileInfo fileData, string fileContentType)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
// set the request variables
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = cookies;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4";
request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*";
request.Headers.Add("Accept-Encoding: gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers.Add("Accept-Language: en-us");
request.Referer = referer;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
// process through the fields
var sbHeader = new StringBuilder();
// add form fields, if any
if (postData != null)
{
foreach (string key in postData.AllKeys)
{
string[] values = postData.GetValues(key);
if (values != null)
{
foreach (string value in values)
{
if (!string.IsNullOrEmpty(value))
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n", key, value);
}
}
}
}
if (fileData != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "media", fileData.Name);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", fileContentType);
}
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;
// set content length
request.ContentLength = contentLength;
// ref http://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
// avoid The request was aborted: Could not create SSL/TLS secure channel exception
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(header, 0, header.Length);
// write the uploaded file
if (fileData != null)
{
// write the file data, if any
byte[] buffer = new Byte[fileData.Length];
var bytesRead = fileData.OpenRead().Read(buffer, 0, (int)(fileData.Length));
requestStream.Write(buffer, 0, bytesRead);
}
// write footer
requestStream.Write(footer, 0, footer.Length);
requestStream.Flush();
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
{
return stIn.ReadToEnd();
}
}
}

Categories