How do you write the below code using UnityWebRequest Put message instead of HttpWebRequest from System.net.
I need to make a PUT call in WebGL, since HttpWebRequest does not work on that platform. I tried to somehow convert it but that did not work for me.
Instead of these two methods, I need one UnityWebRequest Put method.
public static void InvokeHttpRequest(Uri endpointUri, string httpMethod,
IDictionary<string, string> headers, string requestBody)
{
try
{
var request = ConstructWebRequest(endpointUri, httpMethod, headers);
if (!string.IsNullOrEmpty(requestBody))
{
var buffer = new byte[8192]; // arbitrary buffer size
var requestStream = request.GetRequestStream();
using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
{
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
}
CheckResponse(request);
}
catch (WebException ex)
{
using (var response = ex.Response as HttpWebResponse)
{
if (response != null)
{
var errorMsg = ReadResponseBody(response);
Debug.LogError(
$"\n-- HTTP call failed with exception '{errorMsg}'," +
$" status code '{response.StatusCode}'");
}
}
}
}
public static HttpWebRequest ConstructWebRequest(Uri endpointUri, string httpMethod,
IDictionary<string, string> headers)
{
var request = (HttpWebRequest) WebRequest.Create(endpointUri);
request.Method = httpMethod;
foreach (var header in headers.Keys)
{
// not all headers can be set via the dictionary
if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
{
request.Host = headers[header];
}
else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
{
request.ContentLength = long.Parse(headers[header]);
}
else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
{
request.ContentType = headers[header];
}
else
{
request.Headers.Add(header, headers[header]);
}
}
return request;
}
private IEnumerator PostRequest(Uri uri, IDictionary<string, string> formHeaders, string contentBody)
{
var uwr = new UnityWebRequest(uri, "PUT");
var contentBytes = new UTF8Encoding().GetBytes(contentBody);
uwr.uploadHandler = new UploadHandlerRaw(contentBytes);
uwr.downloadHandler = new DownloadHandlerBuffer();
foreach (var header in formHeaders.Keys)
{
// not all headers can be set via the dictionary
if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
{
uwr.SetRequestHeader("host", formHeaders[header]);
}
else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
{
uwr.SetRequestHeader("content-length", formHeaders[header]);
}
else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
{
uwr.SetRequestHeader("content-type", formHeaders[header]);
}
else
{
uwr.SetRequestHeader(header, formHeaders[header]);
}
}
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
Related
Hello I Have a request in web form code behind and i like call web api send Object with a property of type IFormCollection, the object properties sending but file not
WebRequest wrqst = WebRequest.Create(URLService + method);
var postData = new StringBuilder();
foreach (string key in form.Keys)
{
postData.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(form[key]));
}
var data = Encoding.ASCII.GetBytes(postData.ToString());
wrqst.Method = "POST";
wrqst.ContentType = "application/x-www-form-urlencoded";
wrqst.ContentLength = data.Length;
using (var stream = wrqst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse oResponse = wrqst.GetResponse();
I Receive file in Request.File
How i can send File?
To send a file in your web API request, you need to use the multipart/form-data content type instead of application/x-www-form-urlencoded.
[HttpPost]
[Route("api/WEB/Pos_PropertyImageSave")]
[Route("api/POS/Pos_PropertyImageSave")]
public HttpResponseMessage Pos_PropertyImageSave()
{
try
{
var request = HttpContext.Current.Request;
bool IsUpload= false;
/******************Image Upload*********************/
if (request.Files["PropertyImage"] != null )
{
obj.AttachemntName = request.Form["AttachemntName"] != null ? request.Form["AttachemntName"].ToString() : "";
obj.AttachemntNo = request.Form["AttachemntNo"] != null ? request.Form["AttachemntNo"].ToString() : "";
HttpPostedFile uploadImage = request.Files["PropertyImage"];
if (uploadImage.ContentLength > 0)
{
//Convert the File data to Byte Array which will be store in database
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadImage.InputStream))
{
bytes = br.ReadBytes(uploadImage.ContentLength);
}
filesInfo file = new filesInfo
{
File_Name = Path.GetFileName(uploadImage.FileName),
File_Type = uploadImage.ContentType,
File_Data = bytes
};
string FilePath = HttpContext.Current.Server.MapPath("~/Upload/") + Path.GetFileName(uploadImage.FileName);
File.WriteAllBytes(FilePath, bytes);
obj.AttachemntType = Path.GetExtension(uploadImage.FileName);
obj.AttachemntImagePath = "../Upload/" + Path.GetFileName(uploadImage.FileName); ;
obj.AttachemntImage = file.File_Data;
// obj.AttachemntName = Convert.ToBase64String(file.File_Data, 0, file.File_Data.Length);
}
IsUpload= true;
/*******************End Of Image Upload*************/
}
if (IsUpload)
{
String sMessage = string.Format("Image has been " + obj.Mode + " successufully.");
Response responseclass = new Response(sMessage, sMessage, ((int)HttpStatusCode.OK), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
else
{
Response responseclass = new Response("", "Image Upload Failed", ((int)HttpStatusCode.NoContent), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
}
catch (Exception ex)
{
FailureResponse responseclass1 = new FailureResponse(ex.Message.ToString(), ((int)HttpStatusCode.BadRequest), false);
HttpResponseMessage response1 = Request.CreateResponse<FailureResponse>(HttpStatusCode.OK, responseclass1);
throw new HttpResponseException(response1);
}
}
public class filesInfo
{
public string File_Name { get; set; }
public string File_Type { get; set; }
public byte[] File_Data { get; set; }
}
I need to upload files from client machine to a remote server and for that i have created a windows application which will work as client. It will select the required file and call the Web API.
Please find my client code as below :
//...other code removed for brevity
private void UploadFile(string filename)
{
Stream ms = new MemoryStream();
using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
var fileInfo = new FileInfo(filename);
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
MultiPartFormUpload multiPartFormUpload = new MultiPartFormUpload();
List<FileInfo> files = new List<FileInfo>() { fileInfo };
try
{
MultiPartFormUpload.UploadResponse response = multiPartFormUpload.Upload("http://localhost:10458/api/Upload", files);
}
catch (Exception ex)
{
throw ex;
}
}
}
public class MultiPartFormUpload
{
public class MimePart
{
NameValueCollection _headers = new NameValueCollection();
byte[] _header;
public NameValueCollection Headers
{
get { return _headers; }
}
public byte[] Header
{
get { return _header; }
}
public long GenerateHeaderFooterData(string boundary)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("--");
stringBuilder.Append(boundary);
stringBuilder.AppendLine();
foreach (string key in _headers.AllKeys)
{
stringBuilder.Append(key);
stringBuilder.Append(": ");
stringBuilder.AppendLine(_headers[key]);
}
stringBuilder.AppendLine();
_header = Encoding.UTF8.GetBytes(stringBuilder.ToString());
return _header.Length + Data.Length + 2;
}
public Stream Data { get; set; }
}
public class UploadResponse
{
public UploadResponse(HttpStatusCode httpStatusCode, string responseBody)
{
HttpStatusCode = httpStatusCode;
ResponseBody = responseBody;
}
public HttpStatusCode HttpStatusCode { get; set; }
public string ResponseBody { get; set; }
}
public UploadResponse Upload(string url, List<FileInfo> files)
{
using (WebClient client = new WebClient())
{
List<MimePart> mimeParts = new List<MimePart>();
try
{
foreach (FileInfo file in files)
{
MimePart part = new MimePart();
string name = file.Extension.Substring(1);
string fileName = file.Name;
part.Headers["Content-Disposition"] = "form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"";
part.Headers["Content-Type"] = "application/octet-stream";
part.Data = new MemoryStream(File.ReadAllBytes(file.FullName));
mimeParts.Add(part);
}
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
client.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary);
long contentLength = 0;
byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
foreach (MimePart mimePart in mimeParts)
{
contentLength += mimePart.GenerateHeaderFooterData(boundary);
}
byte[] buffer = new byte[8192];
byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
int read;
using (MemoryStream memoryStream = new MemoryStream())
{
foreach (MimePart mimePart in mimeParts)
{
memoryStream.Write(mimePart.Header, 0, mimePart.Header.Length);
while ((read = mimePart.Data.Read(buffer, 0, buffer.Length)) > 0)
memoryStream.Write(buffer, 0, read);
mimePart.Data.Dispose();
memoryStream.Write(afterFile, 0, afterFile.Length);
}
memoryStream.Write(_footer, 0, _footer.Length);
byte[] responseBytes = client.UploadData(url, memoryStream.ToArray());
string responseString = Encoding.UTF8.GetString(responseBytes);
return new UploadResponse(HttpStatusCode.OK, responseString);
}
}
catch (Exception ex)
{
foreach (MimePart part in mimeParts)
if (part.Data != null)
part.Data.Dispose();
if (ex.GetType().Name == "WebException")
{
WebException webException = (WebException)ex;
HttpWebResponse response = (HttpWebResponse)webException.Response;
string responseString;
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseString = reader.ReadToEnd();
}
return new UploadResponse(response.StatusCode, responseString);
}
else
{
throw;
}
}
}
}
}
Please find Web API code as below :
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/upload/files");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
I am able to hit the Web API with the client code but fileInfo.Length is coming 0.
Please let me know what i am missing in Client or Web API code. Thanks !
Hi I'm trying to login via https://www.strava.com/session with HttpWebrequest but it doesn't log me in. It gives me an response of 302 which is good but it never redirect me to https://www.strava.com/dashboard.
this is the code that I'm using
Httpclient:
public class HttpClient
{
private const string UserAgent = "Mozilla/5.0";
public CookieCollection CookieCollection;
public HttpWebRequest WebRequest;
public HttpWebResponse WebResponse;
public int code { get; set; }
public string location { get; set; }
public string PostData(string url, string postData, string refer = "")
{
WebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
WebRequest.UserAgent = UserAgent;
WebRequest.Referer = refer;
WebRequest.AllowAutoRedirect =false;
WebRequest.Timeout = 10000;
WebRequest.KeepAlive = true;
WebRequest.CookieContainer = new CookieContainer();
if (CookieCollection != null && CookieCollection.Count > 0)
{
WebRequest.CookieContainer.Add(CookieCollection);
}
WebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
WebRequest.Method = "POST";
try
{
var postBytes = Encoding.UTF8.GetBytes(postData);
WebRequest.ContentLength = postBytes.Length;
var postDataStream = WebRequest.GetRequestStream();
postDataStream.Write(postBytes, 0, postBytes.Length);
postDataStream.Close();
try
{
WebResponse = (HttpWebResponse)WebRequest.GetResponse();
this.code = (int)WebResponse.StatusCode;
this.location = WebResponse.Headers["Location"];
if (WebResponse.StatusCode == HttpStatusCode.OK ||WebResponse.StatusCode == HttpStatusCode.Redirect)
{
WebResponse.Cookies = WebRequest.CookieContainer.GetCookies(WebRequest.RequestUri);
if (WebResponse.Cookies.Count > 0)
{
if (CookieCollection == null)
{
CookieCollection = WebResponse.Cookies;
}
else
{
foreach (Cookie oRespCookie in WebResponse.Cookies)
{
var bMatch = false;
foreach (
var oReqCookie in
CookieCollection.Cast<Cookie>()
.Where(oReqCookie => oReqCookie.Name == oRespCookie.Name))
{
oReqCookie.Value = oRespCookie.Value;
bMatch = true;
break;
}
if (!bMatch)
CookieCollection.Add(oRespCookie);
}
}
}
var reader = new StreamReader(WebResponse.GetResponseStream());
var responseString = reader.ReadToEnd();
reader.Close();
return responseString;
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
var error = reader.ReadToEnd();
return error;
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "Error in posting data" ;
}
public string GetData(string url, string post = "")
{
var responseStr = string.Empty;
WebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
WebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
WebRequest.Method = "GET";
WebRequest.KeepAlive = true;
WebRequest.Credentials = CredentialCache.DefaultCredentials;
WebRequest.UserAgent = UserAgent;
WebRequest.CookieContainer = new CookieContainer();
if (CookieCollection != null && CookieCollection.Count > 0)
{
WebRequest.CookieContainer.Add(CookieCollection);
}
if (!string.IsNullOrEmpty(post))
{
var postBytes = Encoding.UTF8.GetBytes(post);
WebRequest.ContentLength = postBytes.Length;
var postDataStream = WebRequest.GetRequestStream();
postDataStream.Write(postBytes, 0, postBytes.Length);
postDataStream.Close();
}
WebResponse wresp = null;
try
{
wresp = WebRequest.GetResponse();
var downStream = wresp.GetResponseStream();
if (downStream != null)
{
using (var downReader = new StreamReader(downStream))
{
responseStr = downReader.ReadToEnd();
}
}
return responseStr;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
WebRequest = null;
}
return responseStr;
}
}
Getting crfs-token:
private string GetToken()
{
string token = "";
String sourcestring = hc.GetData(loginURL);
Regex metaTag = new Regex(#"<meta[\s]+[^>]*?name[\s]?=[\s""']+(.*?)[\s""']+content[\s]?=[\s""']+(.*?)[""']+.*?>");
foreach (Match m in metaTag.Matches(sourcestring))
{
if (m.Groups[2].Value.Contains("token"))
{
continue;
}
token = m.Groups[2].Value;
}
return token;
}
Custom keyvaluepair
private string PostParam(Dictionary<string, string> data)
{
var sb = new StringBuilder();
var p = new List<string>();
foreach (KeyValuePair<string, string> pair in data)
{
sb.Clear();
sb.Append(pair.Key).Append("=").Append(pair.Value);
p.Add(sb.ToString());
}
var pp = string.Join("&", p);
return pp;
}
Login:
private HttpClient hc = new HttpClient();
Dictionary data = new Dictionary();
data.Add("utf8", "✓");
data.Add("authenticity_token", GetToken());
data.Add("plan", "");
data.Add("email", "email");
data.Add("password", "password");
hc.PostData(sessionURL,WebUtility.UrlEncode(PostParam(data)), loginURL);
Can someone tell me what I'm doing wrong? if I look the request header when trying to login to strava in browser its the same but still it doesn't log me.
I found the problem.
You need to encode only the token (and the UTF8 character), not the full post data.
This works for me (for some reason I need to run the code two times)
// First time says "logged out"
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("utf8", WebUtility.UrlEncode("✓"));
string token = GetToken();
string tokenEncoded = WebUtility.UrlEncode(token);
data.Add("authenticity_token", tokenEncoded);
data.Add("plan", "");
data.Add("email", "youremail");
data.Add("password", "yourpwd");
data.Add("remember_me", "on");
string parameters = PostParam(data);
hc.PostData(sessionURL, parameters, loginURL);
// Second time logs in
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("utf8", WebUtility.UrlEncode("✓"));
string token = GetToken();
string tokenEncoded = WebUtility.UrlEncode(token);
data.Add("authenticity_token", tokenEncoded);
data.Add("plan", "");
data.Add("email", "youremail");
data.Add("password", "yourpwd");
data.Add("remember_me", "on");
string parameters = PostParam(data);
hc.PostData(sessionURL, parameters, loginURL);
Note:
// Keep this on default value "true"
//WebRequest.AllowAutoRedirect = false;
remark: you can use this code (see my previous post) to change activity's status (privacy) after logging in:
Dictionary<string, string> data2 = new Dictionary<string, string>();
data2.Add("utf8", WebUtility.UrlEncode("✓"));
string token2 = GetToken();
string tokenEncoded2 = WebUtility.UrlEncode(token2);
data2.Add("_method", "patch");
data2.Add("authenticity_token", tokenEncoded2);
data2.Add("activity%5Bvisibility%5D", "only_me"); // or "followers_only"
string parameters2 = PostParam(data2);
hc.PostData("https://www.strava.com/activities/youractivityID", parameters2, loginURL);
I have an OpenIdConnect Server I'm connecting to an I would like to forward token data the first time logging in to be stored on the server. Currently I'm doing this to forward the access token
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
I want to send the Profile Data as well but I don't know the proper header.
How can I do something like this:
xhr.setRequestHeader("Authorization-Profile", "Bearer " + user.profile);
Does anyone know the proper header so I can add these claims to the access token.
Here is an example of what we did in one of our project:
Created a common API response class as below:
public class ApiCommonResponse
{
public object Object { get; set; }
public int httpStatus { get; set; }
public string httpErrorMessage { get; set; }
}
And a generic method to call GET and POST API endpoints. This method will map the response to the supplied data model and will return you the object.
public static ApiCommonResponse GetApiData<T>(string token, T dataModel, string apiEndPoint = null)
{
var responseText = "";
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint != null)
{
var request = (HttpWebRequest)WebRequest.Create(apiEndPoint);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Api-Version", "");
try
{
var httpResponse = (HttpWebResponse)request.GetResponse();
var stream = httpResponse.GetResponseStream();
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
responseText = streamReader.ReadToEnd();
}
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
}
var jsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };
apiCommonResponse.Object = JsonConvert.DeserializeObject<T>(responseText, jsonSettings);
apiCommonResponse.httpStatus = 0;
return apiCommonResponse;
}
public static ApiCommonResponse PostApiData<T>(string username, string token, T dataModel, string apiEndPoint = null)
{
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint == null) return null;
var webRequest = WebRequest.Create(apiEndPoint);
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-Api-Version", "");
using (var requeststreams = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(requeststreams))
{
sw.Write(JsonConvert.SerializeObject(dataModel));
}
}
try
{
var httpStatus = (((HttpWebResponse)webRequest.GetResponse()).StatusCode);
var httpMessage = (((HttpWebResponse)webRequest.GetResponse()).StatusDescription);
using (var s = webRequest.GetResponse().GetResponseStream())
{
if (s == null) return null;
using (var sr = new StreamReader(s))
{
var responseObj = sr.ReadToEnd();
if (!string.IsNullOrEmpty(responseObj))
{
apiCommonResponse = JsonConvert.DeserializeObject<ApiCommonResponse>(responseObj);
}
}
apiCommonResponse.httpStatus = (int)httpStatus;
apiCommonResponse.httpErrorMessage = httpMessage;
apiCommonResponse.Object = apiCommonResponse.Object;
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
return apiCommonResponse;
}
Failed to get response for large file HTTP put create file using c#
I am using file watcher service service monitor, when user created file or folder we are uploading to cloud
if file size more than 512 MB it is taking too much time to get the response
here I am confusing here the issue with my code or server
and reason for this error
if any changes on my code suggest me.
{
var fileFolderObj1 = new FileFolder();
var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
code = HttpStatusCode.OK;
HttpWebResponse response = null;
FileInfo f = new FileInfo(filePath);
long filesizeF = f.Length;
try
{
string selectedFile = null;
selectedFile = filePath;
var fi = System.IO.Path.GetFileName(filePath);
////commented for some reason
var postParameters = new Dictionary<string, object>();
postParameters.Add("file", new FileParameter(filePath, ""));
postParameters.Add("parentId", parentId);
postParameters.Add("newName", fi);
postParameters.Add("cloudId", cloudId);
postParameters.Add("isSecure", isSecure);
//postParameters.Add("fileSize", fi.Length);
postParameters.Add("fileSize", filesizeF);
var userAgent = "Desktop";
var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
var uri = new Uri(postURL);
var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
this.SetBasicAuthHeader(createFileRequest, userId, password);
createFileRequest.ContentType = "multipart/form-data";
createFileRequest.Method = "PUT";
createFileRequest.Timeout = System.Threading.Timeout.Infinite;
createFileRequest.KeepAlive = false;/*true;*/
createFileRequest.UserAgent = userAgent;
createFileRequest.CookieContainer = new CookieContainer();
try
{
using (var requestStream = createFileRequest.GetRequestStream())
{
}
using (response = (HttpWebResponse)createFileRequest.GetResponse())
{
StreamReader(response.GetResponseStream()).ReadToEnd();
fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);
}
}
catch (Exception exc)
{
if (response != null)
{
code = response.StatusCode;
}
}
}
catch (Exception exc)
{
}
}
}
private static readonly Encoding encoding = Encoding.UTF8;
private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream, ILogService logService = null)
{
var needsCLRF = false;
foreach (var param in postParameters)
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
var fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0,buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
logService.Debug("WRITEMULTIPART FORM DATA Bufferlent Running :{0}", bytesRead);
}
fileStream.Close();
}
else
{
var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
}
}