本文整理汇总了C#中System.Net.Http.StreamContent类的典型用法代码示例。如果您正苦于以下问题:C# StreamContent类的具体用法?C# StreamContent怎么用?C# StreamContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StreamContent类属于System.Net.Http命名空间,在下文中一共展示了StreamContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: sendPost
public void sendPost()
{
// Définition des variables qui seront envoyés
HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
HttpContent fileStreamContent = new StreamContent(paramFileStream);
//HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
// formData.Add(bytesContent, "file2", "file2");
try
{
var response = client.PostAsync(actionUrl, formData).Result;
MessageBox.Show(response.ToString());
if (!response.IsSuccessStatusCode)
{
MessageBox.Show("Erreur de réponse");
}
}
catch (Exception Error)
{
MessageBox.Show(Error.Message);
}
finally
{
client.CancelPendingRequests();
}
}
}
示例2: File
public async Task<Models.Media> File(Stream fileStream, string name = "", string description = "", string projectId = null)
{
using (var formData = new MultipartFormDataContent())
{
AddStringContent(formData, _client.Authentication.FieldName, _client.Authentication.Value);
AddStringContent(formData, "project_id", projectId);
AddStringContent(formData, "name", name);
AddStringContent(formData, "description", description);
// Add the file stream
var fileContent = new StreamContent(fileStream);
fileContent.Headers.Add("Content-Type", "application/octet-stream");
fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + name + "\"");
formData.Add(fileContent, "file", name);
// HttpClient problem workaround
var boundaryValue = formData.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");
if (boundaryValue != null)
{
boundaryValue.Value = boundaryValue.Value.Replace("\"", string.Empty);
}
// Upload the file
var response = await _client.Post(Client.UploadUrl, formData);
return _client.Hydrate<Models.Media>(response);
}
}
示例3: Upload
public Stream Upload(string url, string filename, Stream fileStream)
{
HttpContent stringContent = new StringContent(filename);
HttpContent fileStreamContent = new StreamContent(fileStream);
using (var handler = new ProgressMessageHandler())
using (var client = HttpClientFactory.Create(handler))
using (var formData = new MultipartFormDataContent())
{
client.Timeout = new TimeSpan(1, 0, 0); // 1 hour should be enough probably
formData.Add(fileStreamContent, "file", filename);
handler.HttpSendProgress += (s, e) =>
{
float prog = (float)e.BytesTransferred / (float)fileStream.Length;
prog = prog > 1 ? 1 : prog;
if (FileProgress != null)
FileProgress(filename, prog);
};
var response_raw = client.PostAsync(url, formData);
var response = response_raw.Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStreamAsync().Result;
}
}
示例4: AddAsync
/// <summary>
/// Add a <see cref="Stream"/> to interplanetary file system.
/// </summary>
/// <param name="stream"></param>
public async Task<MerkleNode> AddAsync(Stream stream)
{
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(streamContent, "file");
try
{
var url = BuildCommand("add");
if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
using (var response = await Api().PostAsync(url, content))
{
await ThrowOnError(response);
var json = await response.Content.ReadAsStringAsync();
if (log.IsDebugEnabled)
log.Debug("RSP " + json);
var r = JObject.Parse(json);
return new MerkleNode((string)r["Hash"]);
}
}
catch (IpfsException)
{
throw;
}
catch (Exception e)
{
throw new IpfsException(e);
}
}
示例5: PutObject
public void PutObject(string bucketName, string key, Stream stream, Dictionary<string, string> metadata, int timeoutInSeconds)
{
var url = GetUrl(bucketName) + "/" + key;
var now = SystemTime.UtcNow;
var payloadHash = RavenAwsHelper.CalculatePayloadHash(stream);
var content = new StreamContent(stream)
{
Headers =
{
{ "x-amz-date", RavenAwsHelper.ConvertToString(now) },
{ "x-amz-content-sha256", payloadHash }
}
};
foreach (var metadataKey in metadata.Keys)
content.Headers.Add("x-amz-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
var headers = ConvertToHeaders(bucketName, content.Headers);
var client = GetClient(TimeSpan.FromSeconds(timeoutInSeconds));
var authorizationHeaderValue = CalculateAuthorizationHeaderValue("PUT", url, now, headers);
client.DefaultRequestHeaders.Authorization = authorizationHeaderValue;
var response = AsyncHelpers.RunSync(() => client.PutAsync(url, content));
if (response.IsSuccessStatusCode)
return;
throw ErrorResponseException.FromResponseMessage(response);
}
示例6: AttachFiles
private void AttachFiles(IMail message, MultipartFormDataContent content)
{
var files = FetchFileBodies(message);
foreach (var file in files)
{
var ifile = file.Value;
var fileContent = new StreamContent(ifile.OpenAsync(FileAccess.Read).Result);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[" + ifile.Name + "]",
FileName = ifile.Name
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
content.Add(fileContent);
}
var streamingFiles = FetchStreamingFileBodies(message);
foreach (KeyValuePair<string, MemoryStream> file in streamingFiles) {
var name = file.Key;
var stream = file.Value;
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[" + name + "]",
FileName = name
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
content.Add(fileContent);
}
}
示例7: ArgumentNullException
HttpContent IHttpContentEncryptor.Decrypt(HttpContent encryptedContent)
{
if (encryptedContent == null)
{
throw new ArgumentNullException("encryptedContent");
}
var encodedString = encryptedContent.ReadAsStringAsync().Result;
using (var encryptedData = new MemoryStream(Convert.FromBase64String(encodedString)))
{
if (encryptedData.Length == 0)
{
return encryptedContent;
}
this.algorithm.Key = this.keyProvider.Key;
this.algorithm.IV = this.keyProvider.IV;
using (var decryptor = algorithm.CreateDecryptor())
{
var cryptoStream = new CryptoStream(encryptedData, decryptor, CryptoStreamMode.Read);
var originData = new MemoryStream((int)encryptedData.Length);
cryptoStream.CopyTo(originData);
originData.Flush();
originData.Position = 0;
var originContent = new StreamContent(originData);
originContent.Headers.ContentType = encryptedContent.Headers.ContentType;
return originContent;
}
}
}
示例8: ReadFromStreamAsyncShouldReturnUploadImageDataTest
public void ReadFromStreamAsyncShouldReturnUploadImageDataTest()
{
ImageMultipartMediaFormatter target = new ImageMultipartMediaFormatter();
Type type = typeof(UploadImageData);
Stream readStream = null;
MultipartContent content = new MultipartContent("form-data");
byte[] content_bytes=new byte[] { 10, 11, 12 };
StreamContent content_part = new StreamContent(new MemoryStream(content_bytes));
content_part.Headers.Add("Content-Disposition", @"form-data; name=fieldName; filename=image.jpg");
content_part.Headers.Add("Content-Type", "image/jpeg");
content.Add(content_part);
IFormatterLogger formatterLogger = null;
var actual = target.ReadFromStreamAsync(type, readStream, content, formatterLogger);
var actualResult = actual.Result;
Assert.IsInstanceOfType(actualResult,typeof(UploadImageData));
Assert.AreEqual(3, (actualResult as UploadImageData).ImageBuffer.Length);
for (int ind = 0; ind < 3; ind++)
{
Assert.AreEqual(content_bytes[ind], (actualResult as UploadImageData).ImageBuffer[ind]);
}
Assert.AreEqual("image.jpg", (actualResult as UploadImageData).FileName);
Assert.AreEqual("image/jpeg", (actualResult as UploadImageData).ImageType);
}
示例9: PutBlob
public void PutBlob(string containerName, string key, Stream stream, Dictionary<string, string> metadata)
{
var url = GetUrl(containerName) + "/" + key;
var now = SystemTime.UtcNow;
var content = new StreamContent(stream)
{
Headers =
{
{ "x-ms-date", now.ToString("R") },
{ "x-ms-version", "2011-08-18" },
{ "x-ms-blob-type", "BlockBlob" },
{ "Content-Length", stream.Length.ToString(CultureInfo.InvariantCulture) }
}
};
foreach (var metadataKey in metadata.Keys)
content.Headers.Add("x-ms-meta-" + metadataKey.ToLower(), metadata[metadataKey]);
var client = GetClient(TimeSpan.FromHours(1));
client.DefaultRequestHeaders.Authorization = CalculateAuthorizationHeaderValue("PUT", url, content.Headers);
var response = AsyncHelpers.RunSync(() => client.PutAsync(url, content));
if (response.IsSuccessStatusCode)
return;
throw ErrorResponseException.FromResponseMessage(response);
}
示例10: SendAsync
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
OwinRequest owinRequest = OwinRequest.Create();
owinRequest.Scheme = request.RequestUri.Scheme;
owinRequest.Method = request.Method.ToString();
owinRequest.Path = request.RequestUri.AbsolutePath;
owinRequest.QueryString = request.RequestUri.Query.TrimStart('?');
owinRequest.CallCancelled = cancellationToken;
foreach (var header in request.Headers)
{
owinRequest.AddHeaderUnmodified(header.Key, header.Value);
}
HttpContent requestContent = request.Content;
if (requestContent != null)
{
foreach (var header in request.Content.Headers)
{
owinRequest.AddHeaderUnmodified(header.Key, header.Value);
}
}
else
{
requestContent = new StreamContent(Stream.Null);
}
return requestContent.ReadAsStreamAsync()
.Then(requestBody =>
{
owinRequest.Body = requestBody;
var responseMemoryStream = new MemoryStream();
var owinResponse = new OwinResponse(owinRequest)
{
Body = responseMemoryStream
};
return _invoke.Invoke(owinRequest.Dictionary)
.Then(() =>
{
var response = new HttpResponseMessage();
response.StatusCode = (HttpStatusCode)owinResponse.StatusCode;
response.ReasonPhrase = owinResponse.ReasonPhrase;
response.RequestMessage = request;
// response.Version = owinResponse.Protocol;
responseMemoryStream.Seek(0, SeekOrigin.Begin);
response.Content = new StreamContent(responseMemoryStream);
foreach (var header in owinResponse.Headers)
{
if (!response.Headers.TryAddWithoutValidation(header.Key, header.Value))
{
response.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
return response;
});
});
}
示例11: UploadImgur
public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream)
{
try
{
var imageData = new byte[fileStream.Size];
for (int i = 0; i < imageData.Length; i++)
{
imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte();
}
var theAuthClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image");
request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157");
var form = new MultipartFormDataContent();
var t = new StreamContent(fileStream.AsStream());
// TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64.
string base64Img = Convert.ToBase64String(imageData);
t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(new StringContent(base64Img), @"image");
form.Add(new StringContent("file"), "type");
request.Content = form;
HttpResponseMessage response = await theAuthClient.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
if (responseString == null) return null;
var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString);
return imgurEntity;
}
catch (WebException)
{
}
catch (IOException)
{
return null;
}
return null;
}
示例12: ConvertToStreamContent
private StreamContent ConvertToStreamContent(HttpContent originalContent)
{
if (originalContent == null)
{
return null;
}
StreamContent streamContent = originalContent as StreamContent;
if (streamContent != null)
{
return streamContent;
}
MemoryStream ms = new MemoryStream();
originalContent.CopyToAsync(ms).Wait();
ms.Position = 0;
streamContent = new StreamContent(ms);
foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
{
streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return streamContent;
}
示例13: UpdloadFileForSharing
public Guid UpdloadFileForSharing(string filename,string apiKey, string projectName /*,string ownerEmail*/)
{
if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentNullException("filename"); }
if (string.IsNullOrWhiteSpace(apiKey)) { throw new ArgumentNullException("apiKey"); }
if (string.IsNullOrWhiteSpace(projectName)) { throw new ArgumentNullException("projectName"); }
// if (string.IsNullOrWhiteSpace(ownerEmail)) { throw new ArgumentNullException("ownerEmail"); }
if (!File.Exists(filename)) {
throw new FileNotFoundException(filename);
}
string baseUrl = Settings.Default.LocanServiceBaseUrl;
string urlForSharing = string.Format(
"{0}/{1}",
baseUrl,
Consts.UrlAddPhrasesForTranslation);
Guid userId = this.GetUserIdForApiKey(apiKey);
LocanWebFile webFile = this.GetTranslationFile(apiKey, filename, userId, projectName);
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
byte[]bytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(webFile));
using (HttpClient client = new HttpClient())
using(MemoryStream stream = new MemoryStream(bytes)){
StreamContent streamContent = new StreamContent(stream);
HttpResponseMessage response = client.Post(urlForSharing, streamContent);
response.EnsureSuccessStatusCode();
string guidString = response.Content.ReadAsString();
// Result looks like: <?xml version="1.0" encoding="utf-8"?><guid>2158e8e5-ae6c-4b9a-a7ab-3169fff9750d</guid>
XDocument doc = XDocument.Parse(guidString);
return new Guid(doc.Root.Value);
}
}
示例14: UploadMessageAsync
/// <inheritdoc/>
public async Task<Uri> UploadMessageAsync(Stream content, DateTime expirationUtc, string contentType = null, string contentEncoding = null, IProgress<int> bytesCopiedProgress = null, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(content, nameof(content));
Verify.Operation(this.HttpClient != null, $"{nameof(this.HttpClient)} must be set first.");
var httpContent = new StreamContent(content.ReadStreamWithProgress(bytesCopiedProgress));
if (content.CanSeek)
{
httpContent.Headers.ContentLength = content.Length;
}
if (contentType != null)
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
}
if (contentEncoding != null)
{
httpContent.Headers.ContentEncoding.Add(contentEncoding);
}
int lifetime = expirationUtc == DateTime.MaxValue ? int.MaxValue : (int)(expirationUtc - DateTime.UtcNow).TotalMinutes;
var response = await this.HttpClient.PostAsync(this.BlobPostUrl.AbsoluteUri + "?lifetimeInMinutes=" + lifetime, httpContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var serializer = new DataContractJsonSerializer(typeof(string));
var location = (string)serializer.ReadObject(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
return new Uri(location, UriKind.Absolute);
}
示例15: UploadFile
/// <summary>
/// Uploads a file to the specified endpoint
/// </summary>
/// <param name="token">The authentication token</param>
/// <param name="path">The endpoint to invoke</param>
/// <param name="filename">The local file system path to the file</param>
/// <param name="contentType">The mime-type</param>
/// <returns>The result of the operation</returns>
internal async Task<string> UploadFile(AuthToken token, string path, string filename, string contentType)
{
using (HttpClient client = new HttpClient())
{
HttpRequestMessage message = new HttpRequestMessage();
message.Method = HttpMethod.Post;
message.RequestUri = new Uri($"{_baseAddress}/{path}");
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
var content =
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
var streamContent = new StreamContent(File.OpenRead(filename));
streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
content.Add(streamContent, Path.GetFileName(filename), Path.GetFileName(filename));
message.Content = content;
var response =
await client.SendAsync(message);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new ApplicationException($"{response.StatusCode} {response.ReasonPhrase}");
}
}
}