本文整理汇总了C#中System.Net.Http.StringContent.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# StringContent.Dispose方法的具体用法?C# StringContent.Dispose怎么用?C# StringContent.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.StringContent
的用法示例。
在下文中一共展示了StringContent.Dispose方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadAccessTokensAsync
public void LoadAccessTokensAsync(Action<Task<HttpResponseMessage>> onSuccess, Action<Task<HttpResponseMessage>> onError)
{
if (string.IsNullOrWhiteSpace(Communicator.Instance.AuthorizationToken))
{
return;
}
var contentString = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
Communicator.Instance.AuthorizationToken,
Communicator.Instance.ClientId,
Communicator.Instance.ClientSecret,
Communicator.Instance.RedirectUri);
var content = new StringContent(contentString);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
var postTask = _client.PostAsync(Communicator.Instance.TokenRequestUrl, content);
postTask.
ContinueWith(t =>
{
content.Dispose();
if (t.IsFaulted)
{
if (onError != null)
{
onError(t);
}
}
else
{
var readTask = t.Result.Content.ReadAsStringAsync();
readTask.Wait();
var response = readTask.Result.FromJson<AccessTokensResponse>();
Communicator.Instance.AccessToken = response.access_token;
Communicator.Instance.RefreshToken = response.refresh_token;
Communicator.Instance.ExpiresIn = response.expires_in;
if (onSuccess != null)
{
onSuccess(t);
}
}
});
}
示例2: CreateEmptyContentHeaders
public static HttpContentHeaders CreateEmptyContentHeaders()
{
HttpContent httpContent = null;
HttpContentHeaders httpContentHeaders = null;
try
{
httpContent = new StringContent(string.Empty);
httpContentHeaders = httpContent.Headers;
httpContentHeaders.Clear();
}
finally
{
if (httpContent != null)
{
httpContent.Dispose();
}
}
return httpContentHeaders;
}
示例3: CreateEmptyContentHeaders
/// <summary>
/// Creates an empty <see cref="HttpContentHeaders"/> instance. The only way is to get it from a dummy
/// <see cref="HttpContent"/> instance.
/// </summary>
/// <returns>The created instance.</returns>
public static HttpContentHeaders CreateEmptyContentHeaders()
{
HttpContent tempContent = null;
HttpContentHeaders contentHeaders = null;
try
{
tempContent = new StringContent(String.Empty);
contentHeaders = tempContent.Headers;
contentHeaders.Clear();
}
finally
{
// We can dispose the content without touching the headers
if (tempContent != null)
{
tempContent.Dispose();
}
}
return contentHeaders;
}
示例4: SendAsync
private async Task<HttpResponseMessage> SendAsync(Uri uri, List<KeyValuePair<string, string>> headers, string content, string httpMethod)
{
HttpClient client = (HttpClient)null;
HttpRequestMessage request = (HttpRequestMessage)null;
StringContent sc = (StringContent)null;
HttpResponseMessage httpResponseMessage1;
try
{
client = this.CreateClient();
if (headers != null)
{
foreach (KeyValuePair<string, string> keyValuePair in headers)
{
KeyValuePair<string, string> header = keyValuePair;
client.DefaultRequestHeaders.Add(header.Key, header.Value);
header = new KeyValuePair<string, string>();
}
//List<KeyValuePair<string, string>>.Enumerator enumerator = new List<KeyValuePair<string, string>>.Enumerator();
}
sc = new StringContent(content, Encoding.UTF8, "application/json");
HttpMethod method = new HttpMethod(httpMethod);
request = new HttpRequestMessage()
{
Content = (HttpContent)sc,
Method = method,
RequestUri = uri
};
HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
HttpResponseMessage responseMessage = httpResponseMessage;
httpResponseMessage = (HttpResponseMessage)null;
httpResponseMessage1 = responseMessage;
}
finally
{
if (client != null)
client.Dispose();
if (request != null)
request.Dispose();
if (sc != null)
sc.Dispose();
}
return httpResponseMessage1;
}
示例5: GetPostResponseAsync
public async Task<string> GetPostResponseAsync()
{
string DateFrom = DateTime.Now.AddMonths(-12).ToString("yyyy-MM-ddTHH:mm:ss") + ".000Z";
string request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://pointprogress.com/\">" +
"<SOAP-ENV:Body>" +
"<ns1:GetFullClaimLinesAuth >" +
"<ns1:userGuid>" + StateUtilities.LoginHeaders.UserGuid + "</ns1:userGuid>" +
"<ns1:passwordShar>" + StateUtilities.LoginHeaders.UserShar + "</ns1:passwordShar>" +
"<ns1:headerFromDate>" + DateFrom + "</ns1:headerFromDate>" +
"<ns1:detailFromDate>" + DateFrom + "</ns1:detailFromDate>" +
"</ns1:GetFullClaimLinesAuth>" +
"</SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
//2015-12-04T14:47:52.740Z
Dictionary<String, string> parameters = new Dictionary<string, string>();
parameters.Add("SoapAction", "GetFullClaimLinesAuth");
string Url = "https://halcyontek.myexpensesonline.co.uk/webservices/dx.data/dxdatamobile.asmx?wsdl";
Url = AppConstants.BaseURl;
string result = string.Empty;
try
{
//for ssl certificate
HttpClient client = new HttpClient();
if (parameters != null && parameters.Count > 0)
{
foreach (var header in parameters)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
HttpContent content = new StringContent(request);
content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("text/xml");
var response = await client.PostAsync(Url, content);
if (response.IsSuccessStatusCode)
{
var soapResponse = await response.Content.ReadAsStringAsync();
string resp = await RemoveAllNamespaces(soapResponse.ToString());
XDocument document = XDocument.Parse(resp);
var XMLresult = document.Root.Descendants("GetFullClaimLinesAuthResponse");
GetFullClaimLinesAuthResponse GetFullClaimLinesAuthResponse = new GetFullClaimLinesAuthResponse();
foreach (var item in XMLresult)
{
GetFullClaimLinesAuthResponse = CommonFUnction.DeSerializeData<GetFullClaimLinesAuthResponse>(GetFullClaimLinesAuthResponse, item.ToString());
}
if (GetFullClaimLinesAuthResponse != null)
{
List<AuthClaimHeadersDT> listClaimHeadersDT = GetFullClaimLinesAuthResponse.GetFullClaimLinesAuthResult.ReturnedDataTable.Diffgram.ClaimHeaders.AuthClaimHeadersDT;
StateUtilities.ListAuthClaimDetailsDT = GetFullClaimLinesAuthResponse.GetFullClaimLinesAuthResult.SecondaryReturnedDataTable.Diffgram.ClaimDetails.AuthClaimDetailsDT;
await InserttoDB(listClaimHeadersDT, StateUtilities.ListAuthClaimDetailsDT);
await BindData(listClaimHeadersDT, StateUtilities.ListAuthClaimDetailsDT);
pgRing.Visibility = Visibility.Collapsed;
}
}
else
result = DateTime.Now.ToString();
response.Dispose();
response = null;
content.Dispose();
content = null;
client.Dispose();
client = null;
// filter.IgnorableServerCertificateErrors.Clear();
}
catch (Exception ex)
{
result = string.Empty;
}
return result;
}
示例6: LoginAsync
public static async Task<bool> LoginAsync(string data)
{
string authenticationURL = "https://ivle.nus.edu.sg/api/Lapi.svc/Login_JSON";
HttpClient client = new HttpClient();
// encode the request content in url encoding format
HttpContent payload = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = client.PostAsync(authenticationURL, payload).Result;
// wait for the string response
string responseString = await response.Content.ReadAsStringAsync();
// remove the last "}"
responseString = responseString.Remove(responseString.Length - 1);
// remove the first "{" and its associated header
responseString = responseString.Substring(responseString.IndexOf(":") + 1);
// store the newly received token
_token = JsonConvert.DeserializeObject<DataStructure.Token>(responseString);
payload.Dispose();
response.Dispose();
client.Dispose();
return (_token != null && _token.TokenSuccess);
}
示例7: UploadExtensionLibraryAsync
public void UploadExtensionLibraryAsync(string selectedFileName, byte[] fileContents, ObservableCollection<string> assemblies, object userState)
{
Uri uri = CreateRestRequest("Extensions/Upload");
var assembliesString = assemblies != null ? string.Join(",", assemblies) : null;
var content = new MultipartFormDataContent();
var ms = new MemoryStream(fileContents);
var fileContent = new StreamContent(ms);
// Specify the content disposition and content type - without this the form data will not
// be included in the Request object in .NET 2.0 app pools
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + selectedFileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-silverlight-app");
content.Add(fileContent);
var stringContent = new StringContent(assembliesString);
// Need to specify the content disposition and content type for .NET 2.0 compatibility here, too
stringContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"assemblies\""
};
stringContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
content.Add(stringContent);
var client = new HttpClient();
client.PostAsync(uri, content).ContinueWith(t =>
{
stringContent.Dispose();
fileContent.Dispose();
ms.Dispose();
content.Dispose();
if (t.IsCanceled)
return;
if (t.Exception != null)
{
var errorDisplay = new ErrorDisplay();
// Attempt to get the stack trace with IL offsets
string stackTraceIL = t.Exception.StackTraceIL();
ErrorData data = new ErrorData()
{
Message = t.Exception.Message,
StackTrace = !string.IsNullOrEmpty(stackTraceIL) ? stackTraceIL :
t.Exception.StackTrace
};
errorDisplay.DataContext = data;
// Size the error UI
double width = Application.Current.RootVisual.RenderSize.Width * 0.67;
errorDisplay.Width = width > errorDisplay.MaxWidth ? errorDisplay.MaxWidth : width;
errorDisplay.Completed += (o, a) => BuilderApplication.Instance.HideWindow(errorDisplay);
// Show the error
BuilderApplication.Instance.ShowWindow(Strings.ErrorOccured, errorDisplay, false, null, null);
}
if (UploadExtensionLibraryCompleted != null)
{
UploadExtensionLibraryCompleted(this, new UploadExtensionLibraryCompletedEventArgs()
{
Error = t.Exception,
UserState = userState,
});
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
示例8: Get
public override async System.Threading.Tasks.Task<WindDataLib.CreditInfo> Get(string username, string password, string type, Guid dev_id)
{
httpclient.DefaultRequestHeaders.Clear();
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", shitAuthorization);
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/xml;charset=UTF-8");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("x-h3g-msisdn", "39" + username);
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Date", "Thu, 08 May 2014 20:22:42 GMT");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "NativeHost");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "file://,/Applications/Install/443D0ECE-0B8F-4D98-AD73-4304A7CAC910/Install/");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("jsessionid", "1");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("resource", "/serviceExposer/soap/selfcare/credential");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("siteid", "11");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "identity");
var cnt = new StringContent(string.Format(H3GStrings.Login, "39" + username, password), Encoding.UTF8, "text/xml");
cnt.Headers.Clear();
cnt.Headers.TryAddWithoutValidation("Content-Type", "text/xml;charset=UTF-8");
cnt.Headers.ContentType = new md(cnt.Headers.ContentType);
var response = await httpclient.PostAsync(string.Concat(baseUrl, "api/services/credentialService"), cnt).ConfigureAwait(false);
cnt.Dispose();
cnt = new StringContent(string.Format(H3GStrings.InfoRapidService, "39" + username), Encoding.UTF8, "text/xml");
cnt.Headers.Clear();
cnt.Headers.TryAddWithoutValidation("Content-Type", "text/xml;charset=UTF-8");
cnt.Headers.ContentType = new md(cnt.Headers.ContentType);
response = await httpclient.PostAsync(string.Concat(baseUrl, "api/services/infoRapideService"), cnt);
var xml = await response.Content.ReadAsStringAsync();
var xmlDoc = XDocument.Parse(xml);
float credit = 0;
if (xmlDoc.Descendants().Any(x => x.Name.LocalName == "totalCreditAmount"))
credit = float.Parse(xmlDoc.Descendants().First(x => x.Name.LocalName == "totalCreditAmount").Value, CultureInfo.GetCultureInfo("en-US"));
var number = new NumberInfo { Number = username, LastUpdate = DateTime.Now, Credit = credit, SMS = -1, Gigabytes = -1, Minutes = -1, ExpirationDate = DateTime.MaxValue };
var UnitsNodes = xmlDoc.XPathSelectElements("//data[key='freetUnits']");
foreach (var node in UnitsNodes.Descendants().Where(a => a.Attributes().Any(x => x.Name.LocalName == "type" && x.Value == "ns1:FreeUnitItems")))
{
foreach (var el in node.Elements())
{
var dataElem = el.Elements().First(x => x.Name.LocalName != "key");
var initial = float.Parse(dataElem.Elements().First(x => x.Name.LocalName == "initialAmount").Value, CultureInfo.GetCultureInfo("en-US"));
var remaining = float.Parse(dataElem.Elements().First(x => x.Name.LocalName == "remainingAmount").Value, CultureInfo.GetCultureInfo("en-US"));
DateTime expiration = DateTime.Parse(dataElem.Elements().First(x => x.Name.LocalName == "endDate").Value, CultureInfo.GetCultureInfo("en-US"));
number.ExpirationDate = (expiration > number.ExpirationDate ? number.ExpirationDate : expiration);
#if DEBUG
Debug.WriteLine("{0}-{1}-{2}", el.Elements().First(x => x.Name.LocalName == "key").Value, remaining, initial);
#endif
switch (el.Elements().First(x => x.Name.LocalName == "key").Value)
{
case "384":
case "501":
case "498":
case "490":
case "531":
case "535":
case "493":
case "504":
case "364":
case "507":
number.Gigabytes = Math.Max(number.Gigabytes,0);
number.Gigabytes += (int)remaining;
number.GigabytesTotal += initial;
break;
case "194":
case "500":
case "497":
case "489":
case "492":
case "503":
case "363":
case "506":
number.SMS = Math.Max(number.SMS, 0);
number.SMS += (int)remaining;
number.SMSTotal += (int)initial;
break;
case "193":
case "499":
case "488":
case "491":
case "502":
case "362":
case "496":
case "505":
number.Minutes = Math.Max(number.Minutes, 0);
number.Minutes += (int)remaining / 60;
number.MinutesTotal += (int)initial / 60;
break;
}
}
//.........这里部分代码省略.........