Xamarin Forms - 无法设置HttpWebRequest的ContentLenght [英] Xamarin Forms - Cannot set the ContentLenght of HttpWebRequest

查看:197
本文介绍了Xamarin Forms - 无法设置HttpWebRequest的ContentLenght的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用GET和参数来获取请求。但是,我得到WinPhone8.1的一个例外,它因为添加了内容而认为GET是违规协议。所以提出POST请求是解决方案。



尽管我的搜索,我仍然无法设置我的HttpWebRequest的内容lenght属性..为什么?

 私有静态异步void AsyncRequest(string url,string contentType,string methodType,int contentLenght,Action< Object,string> callback,Action< HttpStatusCode,JObject,Action< Object,string>> parserFunction)
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = methodType;
request.Proxy = null;

if(methodType == Method.POST)
{
request.ContentLenght =contentLenght;
request.Headers [content-length] =contentLenght;
request.Headers [Content-Length] =contentLenght;
request.Headers [HttpRequestHeader.ContentLength] =contentLenght;
request.Headers [HttpRequestHeader.ContentLength] =contentLenght;
request.Content.Headers.ContentLength =contentLenght;

...........

什么都不行><
}

Debug.WriteLine(1);
任务< WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
Debug.WriteLine(2);

await task.ContinueWith(t => ReadStreamFromResponse(t.Result,callback,parserFunction));
}


解决方案

感谢 jsonmcgraw :关于 Xamarin论坛<的答案/ a>



如果你想要发出一个GET请求的POST请求,那么有两种方法可以让你能够发出GET / POST请求。 / p>

所以,首先是异步GET请求。

  public static async任务<串GT; MakeGetRequest(string url,string cookie)
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
request.ContentType =text / html;
request.Method =GET;
request.Headers [Cookie] = cookie;

var response = await request.GetResponseAsync();
var respStream = response.GetResponseStream();
respStream.Flush();

使用(StreamReader sr = new StreamReader(respStream)){
//需要返回此响应
string strContent = sr.ReadToEnd();
respStream = null;
返回strContent;
}
}

样本用法:

  public static async Task< MyModel []> GetInfoAsync(int page,string searchString,string cookie)
{
string url = Constants.url + Constants.Path +
page =+ page +
& searchString = + searchString;

string result = await WebControl.MakeGetRequest(url,cookie);

MyModel [] models = Newtonsoft.Json.JsonConvert.DeserializeObject< MyModel []> (结果);

返回型号;
}

接下来,异步POST请求

  public static async Task< string> MakePostRequest(string url,string data,string cookie,bool isJson = true)
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
if(isJson)
request.ContentType =application / json;
else
request.ContentType =application / x-www-form-urlencoded;
request.Method =POST;
request.Headers [Cookie] = cookie;
var stream = await request.GetRequestStreamAsync();
using(var writer = new StreamWriter(stream)){
writer.Write(data);
writer.Flush();
writer.Dispose();
}

var response = await request.GetResponseAsync();
var respStream = response.GetResponseStream();


使用(StreamReader sr = new StreamReader(respStream)){
//需要返回此响应
return sr.ReadToEnd();
}
}

样本用法:

  public static async Task< ResultModel> PostInfoAsync(int id,string cookie)
{

string data =id =+ id;
//第三个参数意味着内容类型不是json
string resp = await WebControl.MakePostRequest(Constants.url + Constants.Path,data,cookie,false);
ResultModel模型;

try {
model = JsonConvert.DeserializeObject< ResultModel> (RESP);
}
catch(例外){
model = new ResultModel {isSuccess = false,Message = resp};
}

返回模型;
}


I tried to mke a request with GET and parameters. However, I got an exception for the WinPhone8.1 which meaned that GET was a violation protocol due to a content added in. So making a POST request is the solution.

Despite my searches, I'm still not able to set the content lenght property of my HttpWebRequest.. Why?

private static async void AsyncRequest(string url, string contentType, string methodType, int contentLenght, Action<Object, string> callback, Action<HttpStatusCode, JObject, Action<Object, string>> parserFunction)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = contentType;
        request.Method = methodType;
        request.Proxy = null;

        if (methodType == Method.POST)
        {
            request.ContentLenght = "contentLenght";
            request.Headers["content-length"] = "contentLenght";
            request.Headers["Content-Length"] = "contentLenght";
            request.Headers[HttpRequestHeader.ContentLength] = "contentLenght";
            request.Headers["HttpRequestHeader.ContentLength"] = "contentLenght";
            request.Content.Headers.ContentLength = "contentLenght";

            ...........

            Nothing works ><
        }

        Debug.WriteLine("1");
        Task<WebResponse> task = Task.Factory.FromAsync(
            request.BeginGetResponse,
            asyncResult => request.EndGetResponse(asyncResult),
            (object)null);
        Debug.WriteLine("2");

        await task.ContinueWith(t => ReadStreamFromResponse(t.Result, callback, parserFunction));
    }

解决方案

Thank to jsonmcgraw for its answer on Xamarin Forums

If you want to make a POST request intead of GET request, then there is the two methods which can make you able to make GET/POST requests.

So, first, an async GET request.

public static async Task<string> MakeGetRequest(string url, string cookie)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
    request.ContentType = "text/html";
    request.Method = "GET";
    request.Headers ["Cookie"] = cookie;

    var response = await request.GetResponseAsync ();
    var respStream = response.GetResponseStream();
    respStream.Flush ();

    using (StreamReader sr = new StreamReader (respStream)) {
            //Need to return this response 
        string strContent = sr.ReadToEnd ();
        respStream = null;
            return strContent;
    }
}

Sample usage:

public static async Task<MyModel[]> GetInfoAsync(int page, string searchString, string cookie)
{
    string url = Constants.url + Constants.Path+ 
        "page=" + page + 
        "&searchString=" + searchString;

    string result = await WebControl.MakeGetRequest (url, cookie);

    MyModel[] models = Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel[]> (result);

    return models;
}

Next, an async POST request

public static async Task<string> MakePostRequest (string url, string data, string cookie, bool isJson = true)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
    if (isJson)
        request.ContentType = "application/json";
    else 
        request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";
    request.Headers ["Cookie"] = cookie;
    var stream = await request.GetRequestStreamAsync ();
    using (var writer = new StreamWriter (stream)) {
        writer.Write (data);
        writer.Flush ();
        writer.Dispose ();
    }

    var response = await request.GetResponseAsync ();
    var respStream = response.GetResponseStream();


    using (StreamReader sr = new StreamReader (respStream)) {
        //Need to return this response 
        return sr.ReadToEnd();
    }
}

Sample usage:

public static async Task<ResultModel> PostInfoAsync(int id, string cookie)
{

    string data = "id=" + id;
    //third param means that the content type is not json
    string resp = await WebControl.MakePostRequest (Constants.url + Constants.Path, data, cookie, false);
    ResultModel model;

    try {
        model =  JsonConvert.DeserializeObject<ResultModel> (resp);
    }
    catch (Exception) {
        model = new ResultModel{ isSuccess = false, Message = resp };
    }

    return model;
}

这篇关于Xamarin Forms - 无法设置HttpWebRequest的ContentLenght的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆