本文整理汇总了C#中System.Net.Http.HttpContent类的典型用法代码示例。如果您正苦于以下问题:C# HttpContent类的具体用法?C# HttpContent怎么用?C# HttpContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpContent类属于System.Net.Http命名空间,在下文中一共展示了HttpContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadContentAsync
private static string ReadContentAsync(HttpContent content)
{
Task task = content.LoadIntoBufferAsync();
task.Wait(TimeoutConstant.DefaultTimeout);
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
return content.ReadAsStringAsync().Result;
}
示例2: GetMetadata
/// <summary>
/// Generates a web request to return the user-defined metadata for this container.
/// </summary>
/// <param name="uri">The absolute URI to the container.</param>
/// <param name="timeout">The server timeout interval.</param>
/// <param name="accessCondition">The access condition to apply to the request.</param>
/// <returns>A web request to use to perform the operation.</returns>
public static HttpRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
{
UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
HttpRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext);
request.ApplyAccessCondition(accessCondition);
return request;
}
示例3: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var writer = new StreamWriter(writeStream);
JSON.Serialize(value, writer, _options);
writer.Flush();
return Task.FromResult(writeStream);
}
示例4: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
bool summary = requestMessage.RequestSummary();
if (type == typeof(OperationOutcome))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer, summary);
}
else if (type.IsAssignableFrom(typeof(Resource)))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer, summary);
content.Headers.ContentLocation = resource.ExtractKey().ToUri();
}
else if (type == typeof(FhirResponse))
{
FhirResponse response = (value as FhirResponse);
if (response.HasBody)
FhirSerializer.SerializeResource(response.Resource, writer, summary);
}
writer.Flush();
});
}
示例5: BuildBase64Signature
public static string BuildBase64Signature(
string apiKey,
string appId,
Uri rawUri,
HttpMethod httpMethod,
HttpContent content,
string nonce,
string requestTimeStamp
)
{
var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
var requestHttpMethod = httpMethod.Method;
// Get the content string out of the content.
string requestContentBase64String = ComputeBase64RequestContent(content);
// Rebuild the signature raw data.
var signatureRawData =
$"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";
// Get the api key bytes.
var secretKeyBytes = Convert.FromBase64String(apiKey);
// Get the signature.
var signature = Encoding.UTF8.GetBytes(signatureRawData);
// Create HMAC SHA class with key data.
using (var hmac = new HMACSHA256(secretKeyBytes))
{
return Convert.ToBase64String(hmac.ComputeHash(signature));
}
}
示例6: CompressedContent
public CompressedContent(HttpContent content, string encodingType)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
if (encodingType == null)
{
throw new ArgumentNullException("encodingType");
}
originalContent = content;
this.encodingType = encodingType.ToLowerInvariant();
if (this.encodingType != "gzip" && this.encodingType != "deflate")
{
throw new InvalidOperationException(string.Format("Encoding '{0}' is not supported. Only supports gzip or deflate encoding.", this.encodingType));
}
// copy the headers from the original content
foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
{
Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Headers.ContentEncoding.Add(encodingType);
}
示例7: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
XmlWriter writer = new XmlTextWriter(writeStream, Encoding.UTF8);
// todo: klopt het dat Bundle wel en <?xml ...> header heeft een Resource niet?
// follow up: is now ticket in FhirApi. Check later.
if (type == typeof(OperationOutcome))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer);
}
else if (type == typeof(ResourceEntry))
{
ResourceEntry entry = (ResourceEntry)value;
FhirSerializer.SerializeResource(entry.Resource, writer);
content.Headers.SetFhirTags(entry.Tags);
}
else if (type == typeof(Bundle))
{
FhirSerializer.SerializeBundle((Bundle)value, writer);
}
else if (type == typeof(TagList))
{
FhirSerializer.SerializeTagList((TagList)value, writer);
}
writer.Flush();
});
}
示例8: WriteToStream
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = new MemoryStream(this.videoData))
{
var length = (int)video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (Exception ex)
{
return;
}
finally
{
outputStream.Close();
}
}
示例9: ReadFromStreamAsync
//public JsonFormatter()
//{
// SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
// SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
//}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var task = new TaskCompletionSource<object>();
using (var ms = new MemoryStream())
{
readStream.CopyTo(ms);
//ms.Seek(0, SeekOrigin.Begin);
//var result = JsonSchemaValidator.Instance().Validate(ms, type);
//if (!string.IsNullOrWhiteSpace(result))
// task.SetResult(result);
//else
{
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new JsonTextReader(new StreamReader(ms)))
{
var serializer = new JsonSerializer();
task.SetResult(serializer.Deserialize(reader, type));
}
}
}
return task.Task;
}
示例10: WriteToStream
public void WriteToStream(Type type, object value, Stream stream, HttpContent content)
{
Author author = (Author)value;
Image image = Image.FromFile(@"D:\dev\CodicePlastico\WebApiBook\HelloWebApi\HelloWebApi\Content\Photos\" + author.Name + ".png");
image.Save(stream, ImageFormat.Png);
image.Dispose();
}
示例11: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
return (object)null;
});
}
示例12: IsFileContent
public static bool IsFileContent(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null)
{
throw new ArgumentNullException("parent");
}
if (headers == null)
{
throw new ArgumentNullException("headers");
}
// For form data, Content-Disposition header is a requirement.
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition == null)
{
// If no Content-Disposition header was present.
throw new InvalidOperationException("No Content-Disposition header found");
}
// The file name's existence indicates it is a file data.
if (!string.IsNullOrEmpty(contentDisposition.FileName))
{
return true;
}
return false;
}
示例13: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
HttpContent httpContent,
IFormatterLogger iFormatterLogger)
{
MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();
IEnumerable<HttpContent> contents = parts.Contents;
HttpContent content = contents.FirstOrDefault();
foreach (HttpContent c in contents ) {
if (SupportedMediaTypes.Contains(c.Headers.ContentType)) {
content = c;
break;
}
}
using (var msgStream = await content.ReadAsStreamAsync())
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
TenMsg msg = (TenMsg)js.ReadObject(msgStream);
Debug.WriteLine("msgString: " + msgStream.ToString());
int sender = msg.Sender;
int receiver = msg.Receiver;
byte phoneType = msg.PhoneType;
bool isLocked = msg.IsLocked;
DateTime msgTime = msg.MsgTime;
string msgContent = msg.MsgContent;
Debug.WriteLine("Msg Content: " + msg.MsgContent);
return new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent);
}
}
示例14: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
MultipartMemoryStreamProvider multipartMemoryStreamProvider = await content.ReadAsMultipartAsync();
Collection<HttpContent> contents = multipartMemoryStreamProvider.Contents;
ImageSet imageSet = await contents.FirstOrDefault<HttpContent>((HttpContent c) => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset").ReadAsAsync<ImageSet>();
ImageSet images = imageSet;
Collection<HttpContent> httpContents = multipartMemoryStreamProvider.Contents;
List<HttpContent> list = (
from c in httpContents
where c.Headers.ContentDisposition.Name.NormalizeName().Matches("image\\d+")
select c).ToList<HttpContent>();
images.Images = new List<Image>();
foreach (HttpContent httpContent in list)
{
List<Image> images1 = images.Images;
Image image = new Image();
Image image1 = image;
image1.ImageData = await httpContent.ReadAsByteArrayAsync();
image.MimeType = httpContent.Headers.ContentType.MediaType;
image.FileName = httpContent.Headers.ContentDisposition.FileName.NormalizeName();
images1.Add(image);
images1 = null;
image1 = null;
image = null;
}
return images;
}
示例15: HttpAbfrage
HttpAbfrage(String Ziel, HttpContent content)
{
//################################################################################################
var httpClient = new HttpClient(); // Neue httpClient instanz
//##################################################################################################
// mit Cockies aber nicht zu ende Programmiert weil wir keine Cockies nutzen
CookieContainer cookie = new CookieContainer(); // Cockie Container Construcktor
HttpClientHandler handler = new HttpClientHandler() // nutze beim zugriff cockies
{
};
HttpClient client = new HttpClient(handler as HttpMessageHandler) // neuer http client
{
BaseAddress = new Uri(GlobalData.Uri2 + Ziel + GlobalData.SessionID) // hier wird auch gleich die Session an das ziel angehangen // url aus uri 2 nutzen test2.php
};
handler.UseCookies = false; // beim zugriff cockies nicht zulassen
handler.UseDefaultCredentials = false;
//#################################################################################################
// Jetzt mit POST
// Schritt 4 Abfrage abschicken und ergebnis entgegennehmen
HttpResponseMessage response = await httpClient.PostAsync(client.BaseAddress, content); // schicke die abfrage an die Url , dann warte bis antwort komplett und speicher erst mal alles
GlobalData.HttpResponse = await response.Content.ReadAsStringAsync();
// MessageDialog msgboxRespons = new MessageDialog(GlobalData.HttpResponse);
// await msgboxRespons.ShowAsync(); // Zeige mir an was angekommen ist
return GlobalData.HttpResponse;
}