猿问

Xamarin 中的 x-www-form-urlencoded

我正在开发 Xamarin.Android 应用程序。我必须使用内容类型为 x-www-form-urlencoded 的 rest API。我无法成功调用 Rest API,在此之前,我使用了许多 Web 服务,但我是第一次研究这种类型的 API。我被困在这。我尝试了两种消费方式:


 public static string makePostEncodedRequest(string url, string jsonparams)

    {

        string ret = "";

        var httpwebrequest = (HttpWebRequest)WebRequest.Create(url);

        httpwebrequest.ContentType = "application/x-www-form-urlencoded";

        //httpwebrequest.Accept = Config.JsonHeaderAJ;

        httpwebrequest.Method = Methods.Post.ToString();


        byte[] bytearray = Encoding.UTF8.GetBytes(jsonparams);


        using (var streamWriter = new StreamWriter(httpwebrequest.GetRequestStream(), Encoding.ASCII))

        {

            streamWriter.Write(bytearray);

            streamWriter.Flush();

            streamWriter.Close();

        }


        var httpResponse = (HttpWebResponse)httpwebrequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))

        {

            ret = streamReader.ReadToEnd();

        }

        return ret;

    }       

下一个是:


   Dictionary<string, string> requestParams = new Dictionary<string, string ();


        requestParams.Add("value=", data1);

        requestParams.Add("&value=", data2);


        using (HttpClient client = new HttpClient())

        {

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));


            HttpResponseMessage response = client.PostAsync(Config.DomainURl + Config.StudentLoginUrl, new FormUrlEncodedContent(requestParams)).Result;


            var tokne = response.Content.ReadAsStringAsync().Result;

        }


qq_花开花谢_0
浏览 191回答 1
1回答
随时随地看视频慕课网APP
我要回答