Xamarin Forms - 无法设置 HttpWebRequest 的 ContentLenght

Xamarin Forms - Cannot set the ContentLenght of HttpWebRequest

我尝试使用 GET 和参数发出请求。但是,我得到了 WinPhone8.1 的异常,这意味着由于添加了内容,GET 是违反协议的。因此提出 POST 请求是解决方案。

尽管进行了搜索,但我仍然无法设置 HttpWebRequest 的内容长度 属性。为什么?

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));
    }

感谢 jsonmcgrawXamarin Forums

上的回答

如果您想发出 POST 请求而不是 GET 请求,那么有两种方法可以让您发出 GET/POST 请求。

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

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;
    }
}

示例用法:

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;
}

接下来,异步 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();


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

示例用法:

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;
}