我尝试通过HTTP请求获取和发送数据。 例: HTTP GET(带标题),用于检索标题和正文 HTTP POST(带标题和正文),用于检索标题和正文 我需要使用MvvmCross(Xamarin的Mvvm实现)来操纵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);
});
}
并编写此代码:
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 ();
}
答案 0 :(得分:2)
我找到了解决方案! :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 ();
}