Xamarin Forms - Cannot set the ContentLenght of HttpWebRequest

别等时光非礼了梦想. 提交于 2020-01-05 07:21:09

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/37837204/xamarin-forms-cannot-set-the-contentlenght-of-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!