gpt4 book ai didi

http - Xamarin MvvmCross Http 请求 : How does this work?

转载 作者:可可西里 更新时间:2023-11-01 16:33:28 25 4
gpt4 key购买 nike

我尝试通过 HTTP 请求获取和发送数据。例子:HTTP GET(带 header ),检索 header 和正文HTTP POST(带有 Headers 和 Body),以检索 Headers 和 Body我需要使用 MvvmCross(Mvvm for Xamarin 的一个实现)来操作 Headers 和 Body

对于第一个版本,我开发了:

public static class Http
{

public static async Task<HttpResponseMessage> Get (string url)
{
using(var httpClient = new HttpClient ()) {
HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Get, SharedResources.Api.ServerAddress + url);
request.Headers.Add ("Content-Type", "application/json");
var response = await httpClient.SendAsync (request);
return response;
}
}

public static async Task<HttpResponseMessage> Post (string url, string body = "", string contentType = "application/json")
{
using (var httpClient = new HttpClient ()) {
httpClient.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (contentType));
var response = await httpClient.PostAsync (SharedResources.Api.ServerAddress + url, new StringContent(body));
return response;
}
}
}

对于第二个版本,我已经开发了,但是我不知道如何获取responseString

public static async Task<IAsyncResult> Post (string url, Dictionary<string,string> customHeaders, string body = "", string contentType = "application/json")
{
String finalresult = String.Empty;
HttpWebRequest httpPostWebRequest = (HttpWebRequest)WebRequest.Create (SharedResources.Api.ServerAddress + url);
foreach (var header in customHeaders) {
httpPostWebRequest.Headers [header.Key] = header.Value;
}
Task.Factory.StartNew (() => {

httpPostWebRequest.ContentType = contentType;
httpPostWebRequest.Method = "POST";
return httpPostWebRequest.BeginGetRequestStream ((requestStreamAsyncResult) => {
HttpWebRequest httpWebRequestStream = (HttpWebRequest)requestStreamAsyncResult.AsyncState;
Stream postStream = httpWebRequestStream.EndGetRequestStream (requestStreamAsyncResult);
byte[] byteArray = Encoding.UTF8.GetBytes (body);
postStream.Write (byteArray, 0, body.Length);
httpWebRequestStream.BeginGetResponse ((responseAsyncResult) => {
HttpWebRequest request = (HttpWebRequest)responseAsyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (responseAsyncResult);
Stream streamResponse = response.GetResponseStream ();
StreamReader streamRead = new StreamReader (streamResponse);
string responseString = streamRead.ReadToEnd ();
//**need to return responseString content**
}, httpWebRequestStream);
}, httpPostWebRequest);

});
}

现在,我找到了这个博客条目:http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

并编写这段代码:

public async static Task<String> Post (string url, Dictionary<string, string> headers = null, string body = "", string contentType = "application/json")
{

HttpClientHandler handler = new HttpClientHandler ();
var httpClient = new HttpClient (handler);
HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Post, SharedResources.Api.ServerAddress + url);

if (headers != null) {
foreach (var header in headers) {
request.Headers.Add (header.Key, header.Value);
Mvx.Trace ("Adding {0} header to request, value {1} OK", header.Key, header.Value);

httpClient.DefaultRequestHeaders.Add (header.Key, header.Value);
Mvx.Trace ("Adding {0} header to httpClient, value {1} OK", header.Key, header.Value);
}
}

request.Content = new StringContent (body, Encoding.UTF8, contentType);
Mvx.Trace ("Adding content {0}", await request.Content.ReadAsStringAsync());

if (handler.SupportsTransferEncodingChunked ()) {
//REQUEST
request.Headers.TransferEncodingChunked = true;

// HTTPCLIENT
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
}

Mvx.Trace ("READING request.Headers CONTENT");
foreach (var header in request.Headers) {
foreach (var value in header.Value) {
Mvx.Trace ("{0} : {1}", header.Key, value);
}
}

Mvx.Trace ("READING httpClient.DefaultRequestHeaders CONTENT");
foreach (var header in httpClient.DefaultRequestHeaders) {
foreach (var value in header.Value) {
Mvx.Trace ("{0} : {1}", header.Key, value);
}
}

HttpResponseMessage response = await httpClient.SendAsync (request);
Mvx.Trace ("SendAsync response : {0}", response.ToString ());

return await response.Content.ReadAsStringAsync ();
}

最佳答案

我找到了解决方案! :D

    public async static Task<String> Post (string url, Dictionary<string, string> headers = null, string body = "", string contentType = "application/json")
{
HttpClientHandler handler = new HttpClientHandler ();
var httpClient = new HttpClient (handler);
HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Post, SharedResources.Api.ServerAddress + url);

// add headers
if (headers != null) {
foreach (var header in headers) {
request.Headers.Add (header.Key, header.Value);
httpClient.DefaultRequestHeaders.Add (header.Key, header.Value);
}
}
// set the content
request.Content = new StringContent (body, Encoding.UTF8, contentType);
// set the content length
request.Content.Headers.ContentLength = body.Length;

// set transfer-enconding
if (handler.SupportsTransferEncodingChunked ()) {
bool chuncked = false;
request.Headers.TransferEncodingChunked = chuncked;
httpClient.DefaultRequestHeaders.TransferEncodingChunked = chuncked;
}
// await and return response
HttpResponseMessage response = await httpClient.SendAsync (request);
return await response.Content.ReadAsStringAsync ();
}

关于http - Xamarin MvvmCross Http 请求 : How does this work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com