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

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

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

Validating Certificate with c#

i try to connect website with validating certificate, but it gives always this error:
"Policy Error: 'RemoteCertificateNameMismatch, RemoteCertificateChainErrors'". How can i get rid of these errror? Thanks in advance.
Functions are following:
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
string path = #"E:\ssl_cert.pem";
var pem = File.ReadAllText(path);
byte[] certBuffer = GetBytesFromPEM(pem, "CERTIFICATE");
var certificate = new X509Certificate2(certBuffer);
request.ClientCertificates.Add(new X509Certificate(certificate));
return request;
}
public void Login(string loginPageAddress, string loginData)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
HttpWebRequest request = (HttpWebRequest)this.GetWebRequest(new Uri(loginPageAddress)) ;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(loginData);
request.ContentLength = postBytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}
byte[] GetBytesFromPEM(string pemString, string section)
{
var header = String.Format("-----BEGIN {0}-----", section);
var footer = String.Format("-----END {0}-----", section);
var start = pemString.IndexOf(header, StringComparison.Ordinal);
if (start < 0)
return null;
start += header.Length;
var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;
if (end < 0)
return null;
return Convert.FromBase64String(pemString.Substring(start, end));
}
Login("https://blablabla:12000","Username=ROOT&Pw=ROOT&submit=");

Getting Data from webApi with HttpWebResponse in 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.

Exe destroys itself

I have made an console app (exe) with C#. Application is used to send some http requests to server. It sends json to call server's API to execute some work. I save cookies in environmental variable.
We have noticed some weird behavior with this exe. With some sequence(we were not able to find out what sequence this is) of API calls ( api is called by command line arguments) the exe destroys itself. Its size becomes 0KB from starting 15MB. I have never seen that kind of behavior before. Do you have any idea what could it be?
This is the main part of code that creates http request, and other uploads file...
static public JObject UploadFile(string fileName)
{
HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/File");
string boundaryString = "----SomeRandomText";
requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = WebRequestMethods.Http.Post;
requestToServer.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServer.KeepAlive = false;
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
requestToServer.CookieContainer = cookies;
}
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
string myFileDescriptionContentDisposition = String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes = ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = fileName;
string myFileContentDisposition = String.Format(
"Content-Disposition: form-data;name=\"{0}\"; " + "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes = ascii.GetBytes(myFileContentDisposition);
FileInfo fileInfo = new FileInfo(fileUrl);
long totalRequestBodySize = boundaryStringLineBytes.Length * 2 + lastBoundaryStringLineBytes.Length + myFileDescriptionContentDispositionBytes.Length + myFileContentDispositionBytes.Length + fileInfo.Length;
requestToServer.ContentLength = totalRequestBodySize;
using (Stream s = requestToServer.GetRequestStream())
{
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDisposition.Length);
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
}
fileStream.Close();
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
}
WebResponse response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
JObject jsonResult = JObject.Parse(replyFromServer);
//CreateErrorLog(replyFromServer);
CreateResponse(replyFromServer);
return jsonResult;
}
static public JObject request(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/json.rpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = new CookieContainer();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
httpWebRequest.CookieContainer = cookies;
httpWebRequest.Headers.Add("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString());
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) == null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
else if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
if (cook.Name == "dopinus.e2.session" && cook.Value != Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User))
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JObject jsonResult = JObject.Parse(result);
//CreateErrorLog(result);
CreateResponse(result);
return jsonResult;
}
}
}

submit attachment using HttpWebRequest

I'm trying to submit an attachment to a REST API. attachment is not submitted correctly. I believe that i'm doing something wrong with the request
RunQueryimage("http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg);
public string RunQueryimage(string imagePath)
{
//do get request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://iss.ontimenow.com/api/v2/incidents/");
request.ContentType = "application/octet-stream";
request.Method = "POST";
var webClient = new WebClient();
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
}
You already have a stream open when you create a web request.
Change this:
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
To:
byte[] fileContent = webClient.DownloadData(imagePath);
if (fileContent != null)
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContent, 0, fileContent.Length);
requestStream.Close();
}

Categories