在wp8中的Http POST

时间:2014-12-11 07:38:50

标签: c# windows-phone-8

正如我所看到的那样,我只遇到过具有回调方法的异步http web请求,如: -

    private void getList(string restApiPath, Dictionary<string, string> output, Type type, string label)
    {

        webRequest = (HttpWebRequest)WebRequest.Create(restApiPath);
        path = restApiPath;
        labelValue = label;
        webRequest.Method = "POST";

        webRequest.ContentType = Globals.POST_CONTENT_TYPE;
        webRequest.Headers["st"] = MPFPConstants.serviceType;

        webRequest.BeginGetRequestStream(result =>
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            // End the stream request operation
            Stream postStream = request.EndGetRequestStream(result);

            // Create the post data
            string reqData = Utils.getStringFromList(output);


            string encode = RESTApi.encodeForTokenRequest(reqData);

            byte[] byteArray = Encoding.UTF8.GetBytes(encode);

            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();


            request.BeginGetResponse(new AsyncCallback(GetResponseCallbackForSpecificConditions), request);

        }, webRequest);
    }

    private void GetResponseCallbackForSpecificConditions(IAsyncResult ar)
    {
      //code
     }

如果我们可以为wp8制作同步httpwebrequest,请建议我吗?

2 个答案:

答案 0 :(得分:0)

为什么不尝试这个,它适用于桌面应用程序:

                using (Stream TextRequestStream = UsedWebRequest.GetRequestStream())
                {
                    TextRequestStream.Write(ByteArray, 0, ByteArray.Length);
                    TextRequestStream.Flush();
                }               
                HttpWebResponse TokenWebResponse = (HttpWebResponse)UsedWebRequest.GetResponse();
                Stream ResponseStream = TokenWebResponse.GetResponseStream();
                StreamReader ResponseStreamReader = new StreamReader(ResponseStream);
                string Response = ResponseStreamReader.ReadToEnd();
                ResponseStreamReader.Close();
                ResponseStream.Close();

答案 1 :(得分:0)

为什么不试试restsharp

示例POST代码如下,

RestClient _authClient = new RestClient("https://sample.com/account/login");
RestRequest _credentials = new RestRequest(Method.POST);
_credentials.AddCookie(_cookie[0].Name, _cookie[0].Value);
_credentials.AddParameter("userLogin", _username, ParameterType.GetOrPost);
_credentials.AddParameter("userPassword", _password, ParameterType.GetOrPost);
_credentials.AddParameter("submit", "", ParameterType.GetOrPost);
RestResponse _credentialResponse = (RestResponse)_authClient.Execute(_credentials);
Console.WriteLine("Authentication phase Uri   : " + _credentialResponse.ResponseUri);