Windows Phone 8.1 webrequest POST 得到响应

Windows Phone 8.1 webrequest POST get response

我正在尝试使用 POST 数据发出网络请求并取回响应。我已经让它在 Android 上工作,但它在 Windows Phone 上的工作方式不同,而且我似乎无法让它工作。我目前收到 GetRequestStreamdGetResponse 的错误。我已经用 asyncawait 试过了,但它返回了空指针。我在 Android:

中使用了以下代码
public static string Login(string user, string pwd)
    {
        WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("myurl");
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            LoginData data = new LoginData
            {
                userid = user,
                password = pwd
            };
            var json = JsonConvert.SerializeObject(data);

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Dispose();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            return streamReader.ReadToEnd();
        }
    }

我成功了!答案显示在下面的代码中。

public static string postData;
    public static string responseString;

    public static async Task PostJsonRequest()
    {
        string AuthServiceUri = "myurl"; 
        HttpWebRequest spAuthReq = WebRequest.Create(AuthServiceUri) as HttpWebRequest;
        spAuthReq.ContentType = "application/json";
        spAuthReq.Method = "POST";
        spAuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), spAuthReq);
    }

    public static void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Dispose();
        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
    }

    public static void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);

            Stream streamResponse = response.GetResponseStream();
            StreamReader reader = new StreamReader(streamResponse);
            responseString = reader.ReadToEnd();
            streamResponse.Dispose();
            reader.Dispose();
            response.Dispose();
        }
        catch (Exception e)
        {

        }
    }

    public static void EnterLoginValues(string user, string pwd)
    {
        LoginData data = new LoginData
        {
            userid = user,
            password = pwd
        };
        postData = JsonConvert.SerializeObject(data);
    }