public void HttpPostWithFilesAndParameters3() { // this method sends a file and checks for the number of bytes recieved HttpClient client = new HttpClient(); string url = "http://www.fiddler2.com/sandbox/FileForm.asp"; HttpPost postMethod = new HttpPost(new Uri(url)); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; string fileName = "small-text.txt"; StringBody stringBody1 = new StringBody(Encoding.ASCII, "1", "1_"); multipartEntity.AddBody(stringBody1); FileInfo fi = ResourceManager.GetResourceFileInfo(fileName); FileBody fileBody1 = new FileBody("fileentry", fileName, fi, "text/plain"); multipartEntity.AddBody(fileBody1); StringBody stringBody2 = new StringBody(Encoding.ASCII, "_charset_", "windows-1252"); multipartEntity.AddBody(stringBody2); HttpResponse response = client.Execute(postMethod); Assert.AreEqual(200, response.ResponseCode); string responseString = EntityUtils.ToString(response.Entity); Assert.AreEqual(url, response.RequestUri.AbsoluteUri); Console.Write(responseString); }
public void HttpPostWithFilesAndParameters() { // this method sends an empty file (or no file :) HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri(Constants.HTTP_MULTIPART_POST_200)); MultipartEntity multipartEntity = new MultipartEntity(); StringBody stringBody1 = new StringBody(Encoding.ASCII, "param1", "value1"); multipartEntity.AddBody(stringBody1); StringBody stringBody2 = new StringBody(Encoding.ASCII, "param2", "!#$^&*((<>"); multipartEntity.AddBody(stringBody2); FileBody fileBody1 = new FileBody("photo", "me.file", null); multipartEntity.AddBody(fileBody1); postMethod.Entity = multipartEntity; HttpResponse response = client.Execute(postMethod); Assert.AreEqual(200, response.ResponseCode); string responseString = EntityUtils.ToString(response.Entity); MessageData md = new MessageData(); md.PostParameters.Add(new NameValuePair("param1", "value1")); md.PostParameters.Add(new NameValuePair("param2", "!#$^&*((<>")); md.Files.Add(new NameValuePair("me.file", "0")); Assert.AreEqual(md.ToString(), responseString); Assert.AreEqual(Constants.HTTP_MULTIPART_POST_200, response.RequestUri.AbsoluteUri); Console.Write(responseString); }
public RemoteMultipartRequest(ScheduledExecutorService workExecutor, HttpClientFactory clientFactory, string method, Uri url, MultipartEntity multiPart, IDictionary <string , object> requestHeaders, RemoteRequestCompletionBlock onCompletion) : base(workExecutor , clientFactory, method, url, null, requestHeaders, onCompletion) { this.multiPart = multiPart; }
/// <summary> /// 邮件发送 /// </summary> /// <param name="to"></param> /// <param name="subject"></param> /// <param name="Content"></param> private static void SendMail(string to, string subject, string Content) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send.xml")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; // 不同于登录SendCloud站点的帐号,您需要登录后台创建发信域名,获得对应发信域名下的帐号和密码才可以进行邮件的发送。 multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", "SdCc6gvb")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "XBA游戏网")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "to", to)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", subject)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "html", Content)); //FileInfo fileInfo = new FileInfo(@"c:\SANCH5890V.jpg"); //UTF8FileBody fileBody = new UTF8FileBody("file1", "SANCH5890V.jpg", fileInfo); //multipartEntity.AddBody(fileBody); HttpResponse response = client.Execute(postMethod); if (response.ResponseCode == 200) { LogMsg(" 发送邮件给:" + to + " 请求状态:" + response.ResponseCode + " 发送状态:" + EntityUtils.ToString(response.Entity).Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r", "")); } else { LogMsg(" 发送邮件给:" + to + " 请求状态:" + response.ResponseCode + " 发送状态:" + EntityUtils.ToString(response.Entity).Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r", "")); } //Console.WriteLine("Response Code: " + response.ResponseCode); //Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity)); }
public static void SendWelcomeMail(string userName, string email) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send_template.json")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; multipartEntity.AddBody(new StringBody(Encoding.UTF8, "template_invoke_name", "superjokes_register")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "substitution_vars", "{\"to\": [\"" + email + "\"], \"sub\" : { \"%username%\" : [\"" + userName + "\"]}}")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "superjokes_cn")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", AppConfig.SendCloudKey)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "超级冷笑话")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", "超级冷笑话注册邮件")); CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod); var repCode = response.ResponseCode; var repResult = EntityUtils.ToString(response.Entity); //LogHelper.Info("reg:" + email + repResult + AppConfig.SendCloudKey); //Console.WriteLine("Response Code: " + response.ResponseCode); //Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity)); //Response.Write("Response Code: " + response.ResponseCode); //Response.Write("<br/>"); //Response.Write("Response Content: " + EntityUtils.ToString(response.Entity)); }
public void testCorruptedByteRange() { String eol = "\r\n"; String partString = eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 27-28/30" + eol + eol + "ag" + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 9-9/30" + eol + eol + "e" + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 27-32/30" + eol + eol + "ago" + eol + BOUNDARY + "--" + eol; try { MultipartEntity.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(partString)), BOUNDARY); Assert.Fail("corrupted byte range should throw a parse exception"); } catch (MultipartException) { // expected } }
public static string get_9kw_api_upload(string data) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://www.9kw.eu/index.cgi")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; StringBody stringBody = new StringBody(Encoding.UTF8, "apikey", _9kw.apikey); multipartEntity.AddBody(stringBody); StringBody stringBody3 = new StringBody(Encoding.UTF8, "source", "csapi"); multipartEntity.AddBody(stringBody3); StringBody stringBody2 = new StringBody(Encoding.UTF8, "action", "usercaptchaupload"); multipartEntity.AddBody(stringBody2); FileInfo fileInfo = new FileInfo(@data); FileBody fileBody = new FileBody("file-upload-01", data, fileInfo); multipartEntity.AddBody(fileBody); HttpResponse response = client.Execute(postMethod); return(EntityUtils.ToString(response.Entity)); }
protected MultipartEntity CreateMultipartBody <T>(T entity, string attachmentName, string attachmentPath) where T : BaseParameter { MultipartEntity result = new MultipartEntity(); var kvs = ResolveParameter(entity); foreach (var kv in kvs) { result.AddBody(new StringBody(Encoding.UTF8, kv.Key, kv.Value)); } if (!string.IsNullOrEmpty(attachmentPath)) { FileInfo fileInfo = new FileInfo(attachmentPath); var fileName = Path.GetFileName(attachmentPath); if (string.IsNullOrEmpty(attachmentName)) { attachmentName = fileName; } UTF8FileBody fileBody = new UTF8FileBody(attachmentName, fileName, fileInfo); result.AddBody(fileBody); } return(result); }
public void testEmptyStream() { try { MultipartEntity.FromStream(new MemoryStream(new byte[] {}), BOUNDARY); Assert.Fail("empty stream should throw a parse exception"); } catch (MultipartException) { // expected } }
internal HttpClient InitializeTransport(out MultipartEntity multipartEntity, out HttpPost postMethod) { var client = new HttpClient(); postMethod = new HttpPost(new Uri(_restEndpoint)); multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; return(client); }
private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity) { var files = FetchFileBodies(message); files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + Path.GetFileName(kvp.Key) + "]", Path.GetFileName(kvp.Key), kvp.Value))); var streamingFiles = FetchStreamingFileBodies(message); streamingFiles.ForEach(kvp => multipartEntity.AddBody(new StreamedFileBody(kvp.Value, kvp.Key))); }
/// <summary> /// Old style login. /// Don't know on which devices this is actually used. /// </summary> private void DoOldLogin() { var url = new UriBuilder("https", deviceIp, DevicePort, "/cgi-bin/login.cgi").Uri; var loginEntity = new MultipartEntity(); loginEntity.AddBody(new StringBody(PartEncoding, "user", UserName)); loginEntity.AddBody(new StringBody(PartEncoding, "passwd", password)); httpClient.Post(url, loginEntity); }
/// <summary> /// Perform a command on the AppInstaller. /// </summary> private void DoCommand(string command, string barFilePath, bool includePackageId, bool includePackageName, string packageId) { var url = new UriBuilder("https", deviceIp, DevicePort, "/cgi-bin/appInstaller.cgi").Uri; var entity = new MultipartEntity(); AddParts(entity, command, barFilePath, includePackageId, includePackageName, packageId); var resp = httpClient.Post(url, entity); PrintResult(resp.GetResponseStream()); }
/// <summary> /// Post data onto the given URL and return the response. /// </summary> internal HttpWebResponse Post(Uri uri, MultipartEntity entity) { var request = Initialize(WebRequest.Create(uri)); request.ServicePoint.Expect100Continue = false; request.Method = "POST"; request.ContentLength = entity.ContentLength; request.ContentType = entity.ContentType; var postData = entity.Content; request.GetRequestStream().Write(postData, 0, postData.Length); return((HttpWebResponse)request.GetResponse()); }
public void testPartsNoCR() { String eol = "\n"; String partString = eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 27-28/30" + eol + eol + "ag" + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 9-9/30" + eol + eol + "e" + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 5-5/30" + eol + eol + "s" + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 4-4/30" + eol + eol + " " + eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 27-29/30" + eol + eol + "ago" + eol + BOUNDARY + "--" + eol; MultipartEntity entity = MultipartEntity.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(partString)), BOUNDARY); Assert.AreEqual(entity.Count(), 5, "Wrong number of parts"); Assert.AreEqual(entity[0].ContentType, "text/plain", "Part 1 content type is wrong"); Assert.AreEqual(entity[0].ContentExtent, new Extent(27, 2), "Part 1 range is wrong"); Assert.IsTrue(entity[0].Data.SequenceEqual(Encoding.UTF8.GetBytes("ag")), "Part 1 data is wrong"); Assert.AreEqual(entity[1].ContentType, "text/plain", "Part 2 content type is wrong"); Assert.AreEqual(entity[1].ContentExtent, new Extent(9, 1), "Part 2 range is wrong"); Assert.IsTrue(entity[1].Data.SequenceEqual(Encoding.UTF8.GetBytes("e")), "Part 2 data is wrong"); Assert.AreEqual(entity[2].ContentType, "text/plain", "Part 3 content type is wrong"); Assert.AreEqual(entity[2].ContentExtent, new Extent(5, 1), "Part 3 range is wrong"); Assert.IsTrue(entity[2].Data.SequenceEqual(Encoding.UTF8.GetBytes("s")), "Part 3 data is wrong"); Assert.AreEqual(entity[3].ContentType, "text/plain", "Part 4 content type is wrong"); Assert.AreEqual(entity[3].ContentExtent, new Extent(4, 1), "Part 4 range is wrong"); Assert.IsTrue(entity[3].Data.SequenceEqual(Encoding.UTF8.GetBytes(" ")), "Part 4 data is wrong"); Assert.AreEqual(entity[4].ContentType, "text/plain", "Part 5 content type is wrong"); Assert.AreEqual(entity[4].ContentExtent, new Extent(27, 3), "Part 5 range is wrong"); Assert.IsTrue(entity[4].Data.SequenceEqual(Encoding.UTF8.GetBytes("ago")), "Part 5 data is wrong"); }
public void testOnePart() { String eol = "\n"; String partString = eol + BOUNDARY + eol + "Content-Type: text/plain" + eol + "Content-Range: bytes 27-28/30" + eol + eol + "ag" + eol + BOUNDARY + "--" + eol; MultipartEntity entity = MultipartEntity.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(partString)), BOUNDARY); Assert.AreEqual(entity.Count(), 1, "Wrong number of parts"); Assert.AreEqual(entity[0].ContentType, "text/plain", "Part 1 content type is wrong"); Assert.AreEqual(entity[0].ContentExtent, new Extent(27, 2), "Part 1 range is wrong"); Assert.IsTrue(entity[0].Data.SequenceEqual(Encoding.UTF8.GetBytes("ag")), "Part 1 data is wrong"); }
public static void VerifyNotice(string userName, string email, string jokeTitle, string jokeurl) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send_template.json")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; multipartEntity.AddBody(new StringBody(Encoding.UTF8, "template_invoke_name", "superjokes_verifynotice")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "substitution_vars", "{\"to\": [\"" + email + "\"], \"sub\" : { \"%username%\" : [\"" + userName + "\"],\"%joketitle%\":[\"" + jokeTitle + "\"],\"%jokeurl%\":[\"" + jokeurl + "\"]}}")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "superjokes_cn")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", AppConfig.SendCloudKey)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "超级冷笑话")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", "超级冷笑话审核通知")); CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod); var repCode = response.ResponseCode; var repResult = EntityUtils.ToString(response.Entity); //LogHelper.Info("verify:" + email + repResult + AppConfig.SendCloudKey); }
public string postFile(string session, string fileName) { int GOOD_RETURN_CODE = 200; string subIdLocal = ""; FileStream imageFile = File.OpenRead(fileName); CodeScales.Http.HttpClient httpClient = new CodeScales.Http.HttpClient(); HttpPost httpPost = new HttpPost(new Uri(url + "/api/upload/")); JsonObject jsonObject = getUploadJSON(session); MultipartEntity reqEntity = new MultipartEntity(); StringBody stringBody = new StringBody(Encoding.UTF8, "request-json", jsonObject.ToString()); reqEntity.AddBody(stringBody); FileInfo fileInfo = new FileInfo(fileName); FileBody fileBody = new FileBody("file", fileName, fileInfo); reqEntity.AddBody(fileBody); httpPost.Entity = reqEntity; HttpResponse response = httpClient.Execute(httpPost); String result = ""; int respCode = response.ResponseCode; if (respCode == GOOD_RETURN_CODE) { HttpEntity entity = response.Entity; String content = EntityUtils.ToString(entity); string success = jsonGetValue(content, "status"); subIdLocal = jsonGetValue(content, "subid"); string hash = jsonGetValue(content, "hash"); } return(subIdLocal); }
/// <summary> /// Add parts to the entity. /// </summary> private void AddParts(MultipartEntity entity, string command, string barFilePath, bool includePackageId, bool includePackageName, string packageId) { entity.AddBody(new StringBody(PartEncoding, "command", command)); if (barFilePath != null) { entity.AddBody(new FileBody("file", Path.GetFileName(barFilePath), new FileInfo(barFilePath), "application/zip")); } if (includePackageId || includePackageName) { string name = null; if (packageId == null) { if (barFilePath == null) { throw new ArgumentNullException("barFilePath"); } var barFile = new BarFile(barFilePath); packageId = barFile.Manifest.PackageId; name = barFile.Manifest.PackageName; } if (includePackageId) { if (packageId == null) { throw new ArgumentException("Missing Package-Id"); } entity.AddBody(new StringBody(PartEncoding, "package_id", packageId)); } if (includePackageName || (name != null)) { if (name == null) { throw new ArgumentException("Missing Package-Name"); } entity.AddBody(new StringBody(PartEncoding, "package_name", name)); } } }
public void HttpPostWithFilesAndParameters2() { // this method sends a file and checks for the number of bytes recieved HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri(Constants.HTTP_MULTIPART_POST_200)); MultipartEntity multipartEntity = new MultipartEntity(); string fileName = "big-text.txt"; FileInfo fi = ResourceManager.GetResourceFileInfo(fileName); FileBody fileBody1 = new FileBody("file", fileName, fi, "text/plain"); multipartEntity.AddBody(fileBody1); postMethod.Entity = multipartEntity; StringBody stringBody1 = new StringBody(Encoding.ASCII, "param1", "value1"); multipartEntity.AddBody(stringBody1); StringBody stringBody2 = new StringBody(Encoding.ASCII, "param2", "!#$^&*((<>"); multipartEntity.AddBody(stringBody2); HttpResponse response = client.Execute(postMethod); Assert.AreEqual(200, response.ResponseCode); string responseString = EntityUtils.ToString(response.Entity); MessageData md = new MessageData(); md.PostParameters.Add(new NameValuePair("param1", "value1")); md.PostParameters.Add(new NameValuePair("param2", "!#$^&*((<>")); md.Files.Add(new NameValuePair(fileName, fi.Length.ToString())); Assert.AreEqual(md.ToString(), responseString); Assert.AreEqual(Constants.HTTP_MULTIPART_POST_200, response.RequestUri.AbsoluteUri); Console.Write(responseString); }
//----------------------------------------------------- // // Encryption // //----------------------------------------------------- /// <summary> /// Takes a <see cref="MultipartEntity"/>, encrypts it, and returns a MimeEntity with the associated /// content headers for encrypted content and the encrypted body. /// </summary> /// <param name="entity">The <see cref="MultipartEntity"/>, including content header and body, to encrypt</param> /// <param name="encryptingCertificate">The certificate used for encrytion</param> /// <returns>The encrypted mime entity.</returns> public MimeEntity Encrypt(MultipartEntity entity, X509Certificate2 encryptingCertificate) { return Encrypt(entity.ToEntity(), encryptingCertificate); }
/// <summary> /// Takes a <see cref="MultipartEntity"/>, encrypts it with a collection of certificates, /// and returns a MimeEntity with the associated /// content headers for encrypted content and the encrypted body. /// </summary> /// <remarks> /// As specified in the S/MIME and CMS RFCs, encryption uses symetric encryption to encrypt the body, and /// certificate-based asymetric encryption to encrypt the encryption key used. With multiple certificates, /// there will be multiple copies of the encrypted encryption key. /// </remarks> /// <param name="entity">The <see cref="MultipartEntity"/>, including content header and body, to encrypt</param> /// <param name="encryptingCertificates">The collection of certificate used for encrytion</param> /// <returns>The encrypted mime entity.</returns> public MimeEntity Encrypt(MultipartEntity entity, X509Certificate2Collection encryptingCertificates) { return Encrypt(entity.ToEntity(), encryptingCertificates); }
//----------------------------------------------------- // // Encryption // //----------------------------------------------------- /// <summary> /// Takes a <see cref="MultipartEntity"/>, encrypts it, and returns a MimeEntity with the associated /// content headers for encrypted content and the encrypted body. /// </summary> /// <param name="entity">The <see cref="MultipartEntity"/>, including content header and body, to encrypt</param> /// <param name="encryptingCertificate">The certificate used for encrytion</param> /// <returns>The encrypted mime entity.</returns> public MimeEntity Encrypt(MultipartEntity entity, X509Certificate2 encryptingCertificate) { return(Encrypt(entity.ToEntity(), encryptingCertificate)); }
/// <summary> /// Takes a <see cref="MultipartEntity"/>, encrypts it with a collection of certificates, /// and returns a MimeEntity with the associated /// content headers for encrypted content and the encrypted body. /// </summary> /// <remarks> /// As specified in the S/MIME and CMS RFCs, encryption uses symetric encryption to encrypt the body, and /// certificate-based asymetric encryption to encrypt the encryption key used. With multiple certificates, /// there will be multiple copies of the encrypted encryption key. /// </remarks> /// <param name="entity">The <see cref="MultipartEntity"/>, including content header and body, to encrypt</param> /// <param name="encryptingCertificates">The collection of certificate used for encrytion</param> /// <returns>The encrypted mime entity.</returns> public MimeEntity Encrypt(MultipartEntity entity, X509Certificate2Collection encryptingCertificates) { return(Encrypt(entity.ToEntity(), encryptingCertificates)); }
private void AttachFormParams(ISendGrid message, MultipartEntity multipartEntity) { var formParams = FetchFormParams(message); formParams.ForEach(kvp => multipartEntity.AddBody(new StringBody(Encoding.UTF8, kvp.Key, kvp.Value))); }
/// <summary> /// Updates this entity with the multipart entity, updating headers and body as appropriate. /// </summary> /// <param name="multipartEntity">The mulitpart entity to update.</param> public virtual void UpdateBody(MultipartEntity multipartEntity) { this.SetParts(multipartEntity); }
/// <summary> /// Updates this entity with the multipart entity, updating headers and body as appropriate. /// </summary> /// <param name="entities">The mulitpart entity to update.</param> public void SetParts(MultipartEntity entities) { this.SetParts(entities, MimeSerializer.Default); }
private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity) { var files = FetchFileBodies(message); files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + kvp.Key + "]", kvp.Key, kvp.Value))); }
private bool UploadMultipartRevision(RevisionInternal revision) { MultipartEntity multiPart = null; IDictionary <string, object> revProps = revision.GetProperties(); revProps.Put("_revisions", db.GetRevisionHistoryDict(revision)); // TODO: refactor this to IDictionary <string, object> attachments = (IDictionary <string, object>)revProps.Get ("_attachments"); foreach (string attachmentKey in attachments.Keys) { IDictionary <string, object> attachment = (IDictionary <string, object>)attachments .Get(attachmentKey); if (attachment.ContainsKey("follows")) { if (multiPart == null) { multiPart = new MultipartEntity(); try { string json = Manager.GetObjectMapper().WriteValueAsString(revProps); Encoding utf8charset = Sharpen.Extensions.GetEncoding("UTF-8"); multiPart.AddPart("param1", new StringBody(json, "application/json", utf8charset) ); } catch (IOException e) { throw new ArgumentException(e); } } BlobStore blobStore = this.db.GetAttachments(); string base64Digest = (string)attachment.Get("digest"); BlobKey blobKey = new BlobKey(base64Digest); InputStream inputStream = blobStore.BlobStreamForKey(blobKey); if (inputStream == null) { Log.W(Database.Tag, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision." ); multiPart = null; } else { string contentType = null; if (attachment.ContainsKey("content_type")) { contentType = (string)attachment.Get("content_type"); } else { if (attachment.ContainsKey("content-type")) { string message = string.Format("Found attachment that uses content-type" + " field name instead of content_type (see couchbase-lite-android" + " issue #80): " + attachment); Log.W(Database.Tag, message); } } multiPart.AddPart(attachmentKey, new InputStreamBody(inputStream, contentType, attachmentKey )); } } } if (multiPart == null) { return(false); } string path = string.Format("/%s?new_edits=false", revision.GetDocId()); // TODO: need to throttle these requests Log.D(Database.Tag, "Uploadeding multipart request. Revision: " + revision); Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": uploadMultipartRevision() calling asyncTaskStarted()" ); AsyncTaskStarted(); SendAsyncMultipartRequest("PUT", path, multiPart, new _RemoteRequestCompletionBlock_411 (this)); // TODO: return(true); }
/// <summary> /// Updates this entity with the multipart entity, updating headers and body as appropriate, /// using a custom serializer /// </summary> /// <param name="entities">The mulitpart entity to update.</param> /// <param name="serializer">The serializer to use</param> public void SetParts(MultipartEntity entities, MimeSerializer serializer) { this.SetParts(entities, entities.ContentType.ToString(), serializer); }
private bool UploadMultipartRevision(RevisionInternal revision) { MultipartEntity multiPart = null; IDictionary <string, object> revProps = revision.GetProperties(); // TODO: refactor this to IDictionary <string, object> attachments = (IDictionary <string, object>)revProps.Get ("_attachments"); foreach (string attachmentKey in attachments.Keys) { IDictionary <string, object> attachment = (IDictionary <string, object>)attachments .Get(attachmentKey); if (attachment.ContainsKey("follows")) { if (multiPart == null) { multiPart = new MultipartEntity(); try { string json = Manager.GetObjectMapper().WriteValueAsString(revProps); Encoding utf8charset = Sharpen.Extensions.GetEncoding("UTF-8"); multiPart.AddPart("param1", new StringBody(json, "application/json", utf8charset) ); } catch (IOException e) { throw new ArgumentException(e); } } BlobStore blobStore = this.db.GetAttachments(); string base64Digest = (string)attachment.Get("digest"); BlobKey blobKey = new BlobKey(base64Digest); InputStream inputStream = blobStore.BlobStreamForKey(blobKey); if (inputStream == null) { Log.W(Log.TagSync, "Unable to find blob file for blobKey: %s - Skipping upload of multipart revision." , blobKey); multiPart = null; } else { string contentType = null; if (attachment.ContainsKey("content_type")) { contentType = (string)attachment.Get("content_type"); } else { if (attachment.ContainsKey("content-type")) { Log.W(Log.TagSync, "Found attachment that uses content-type" + " field name instead of content_type (see couchbase-lite-android" + " issue #80): %s", attachment); } } multiPart.AddPart(attachmentKey, new InputStreamBody(inputStream, contentType, attachmentKey )); } } } if (multiPart == null) { return(false); } string path = string.Format("/%s?new_edits=false", revision.GetDocId()); Log.D(Log.TagSync, "Uploading multipart request. Revision: %s", revision); AddToChangesCount(1); Log.V(Log.TagSync, "%s | %s: uploadMultipartRevision() calling asyncTaskStarted()" , this, Sharpen.Thread.CurrentThread()); AsyncTaskStarted(); SendAsyncMultipartRequest("PUT", path, multiPart, new _RemoteRequestCompletionBlock_542 (this, revision)); // Server doesn't like multipart, eh? Fall back to JSON. //status 415 = "bad_content_type" return(true); }