HttpWebRequests的公共类 - WP8

时间:2014-04-10 15:57:31

标签: windows-phone-8 httpwebrequest httpwebresponse

为了进行http调用我使用函数

    private void DoneClicked(object sender, RoutedEventArgs e)
    {
        string emailText = emailTBox.Text;
        string oldPass = oldPasswordPBox.Password;
        string newPass = newPasswordPBox.Password;

        if (emailText == "" || oldPass == "" || newPass == "")
        {
            PassDiaTB1.Text = "Oops..";
            PassDiaTB2.Text = "Some field is empty";
            PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {

            var data = new { user = new { email = emailText, old_password = oldPass, new_password = newPass } };
            jsonStringChild = JsonConvert.SerializeObject(data, Formatting.Indented);

            Debug.WriteLine(jsonStringChild);

            string uri = CycleManager.HTTP_URI + "change-password";
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = CycleManager.HTTP_PUT;
            request.ContentType = "application/json";
            request.Accept = "application/json";

            bool IsNetWork = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

            if (!IsNetWork)
            {
                PassDiaTB1.Text = "Oops..";
                PassDiaTB2.Text = "Check your internet connectivity";
                PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                request.BeginGetRequestStream(new AsyncCallback(PostCallBack), request);
            }
        }

    }

    void PostCallBack(IAsyncResult result)
    {
        // End the stream request operation 

        HttpWebRequest request = result.AsyncState as HttpWebRequest;

        Stream postStream = request.EndGetRequestStream(result);

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

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

        postStream.Close();

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

    }

    void GetResponseStreamCallBack(IAsyncResult callBackResult)
    {
        try
        {
            HttpWebRequest request = callBackResult.AsyncState as HttpWebRequest;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callBackResult);
            statusCode = (int)response.StatusCode;

            if (statusCode == 200)
            {
                string result = "";
                using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
                {
                    result = httpWebStreamReader.ReadToEnd();
                }

                string json = result;

                Dictionary<string, string> token = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                string email = token["email"];
                string auth_token = token["auth_token"];

                CycleManager cycMan = CycleManager.Instance;
                cycMan.AuthToken = auth_token;

                Dispatcher.BeginInvoke(ShowPassiveDialog);

            }
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                HttpWebResponse aResp = e.Response as HttpWebResponse;

                if (aResp != null)
                {
                    statusCode = (int)aResp.StatusCode;
                }

                if (statusCode == 401)
                {
                    string result = "";
                    using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
                    {
                        result = httpWebStreamReader.ReadToEnd();
                    }

                    string json = result;

                    var definition = new { message = "" };

                    var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);

                    message = parsedStrings.message;

                    Dispatcher.BeginInvoke(ShowPassiveDialog);

                }

                if (statusCode == 500)
                {
                    string result = "";
                    using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
                    {
                        result = httpWebStreamReader.ReadToEnd();
                    }

                    string json = result;

                    var definition = new { message = "" };

                    var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);

                    message = parsedStrings.message;

                    Dispatcher.BeginInvoke(ShowPassiveDialog);
                }
            }
        }
    }

在几页中进行相同的三次调用,更改参数和方法。我正在尝试创建一个可以调用http调用的公共类。但是这些函数有不同的返回类型,我不能概括所有这些?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

愿这会引导你。我为这种工作创建了一个包装类,它帮助了我很多并减少了很多代码和工作量。

 public class CommanHttpRequest
  { 

private string ACCEPT="application/json";
private string ContentType ="application/json";
private string POST_METHOD="POST";
private string GET_METHOD="GET";
public string IsException { get; set; }

public HttpWebRequest GetHttpRequest(string url,string header1, string header2)
        {
            HttpWebRequest getRequest = HttpWebRequest.CreateHttp(url);
            getRequest.Accept =this.ACCEPT;
            getRequest.ContentType = this.ACCEPT;
            getRequest.Headers["Header1"] = header1;
            getRequest.Headers["Header2"] = header2;
            getRequest.Method = this.POST_METHOD;
            return getRequest ;
        }



  public void GetRequestResponse(Action<your type> callback, IAsyncResult asyncResult, string envelop)
        {
            try
            {
                UTF8Encoding encoding = new UTF8Encoding();
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                Stream body = request.EndGetRequestStream(asyncResult);
                //write body if any
                byte[] formBytes = encoding.GetBytes(envelop);
                body.Write(formBytes, 0, formBytes.Length);
                body.Close();

                request.BeginGetResponse(result =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                        using (Stream data = response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(data))
                            {
                                string jsonString = reader.ReadToEnd();
                                MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
                                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(your type));
                                var parseddata = dataContractJsonSerializer.ReadObject(memoryStream) as your type;
                                callback(parseddata );
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        IsException = ex.Message;
                        //I asume your type  =List<abc>();
                        callback(new List<abc>());
                    }
                }, request);
            }
            catch (Exception ex)
            {
                IsException = ex.Message;
                callback(new List<abc>());
            }
        }


}

public class abc
{
 public void TestRequest()
        {
            string url="some url";
            CommanHttpRequest requestObj = new CommanHttpRequest();
            HttpWebRequest testRequest = _requestObj.GetHttpRequest(url, password, email);
            //if there some body in request
            string envelope = "{\"requestType\":" + requestType + "}";
            testRequest .BeginGetRequestStream(result =>
            {
                requestObj.GetRequestResponse(resultData =>
                {
                    ProcessServiceResponse(resultData);
                }, result, envelope);
            }, testRequest );
        }

   public void ProcessServiceResponse(List<abc> abcdata)
        {
            //abcdata is your data
        }
}