Xamarin Android中的发布方法

时间:2019-01-04 15:47:26

标签: c# json wcf xamarin.android

我用wcf编码了一个插入服务并将其托管在iis中 现在我想在xamarin android中使用它来开发应用程序
我的一行代码有问题,其他没问题
以下是“我的代码”的一部分:

_btnAdd.Click += delegate
        {
            string sUrl = "http://192.168.43.31/Service1.svc/insertIntoTableAdvertise";
            string sContentType = "application/json";

            JObject oJsonObject = new JObject();
            oJsonObject.Add("TxtGroup", _edtAdvGrouping.Text);
            oJsonObject.Add("TxtTitle", _edtTitle.Text);
            oJsonObject.Add("TxtDate", "0");
            oJsonObject.Add("TxtLocation","شاهین");
            oJsonObject.Add("TxtNumber", _edtNumber.Text);
            oJsonObject.Add("TxtPrice", _edtPrice.Text);
            oJsonObject.Add("TxtExpression", _edtExpression.Text);

            HttpClient oHttpClient = new HttpClient();
            var oTaskPostAsync = oHttpClient.PostAsync(sUrl, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));
            try
            {
                oTaskPostAsync.ContinueWith((oHttpResponseMessage) =>
                {
                    // response of post here
                    //Debug ("webserviceresponse:>" + oHttpResponseMessage);
                    Toast.MakeText(this, oHttpResponseMessage.ToString(), ToastLength.Short);
                });
                oTaskPostAsync.Wait();
            }
            catch (Exception ex)
            {

                Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
            }   

我的问题是这条线:

oTaskPostAsync.ContinueWith((oHttpResponseMessage) =>   {}

部署后,我尝试打印oHttpResponseMessage,但是代码未在ContinueWith中输入。

1 个答案:

答案 0 :(得分:1)

由于使用了HttpClient,因此使客户端保持静态以避免套接字问题

//this should be a field in the class.
static HttpClient httpClient = new HttpClient();

//...

并在事件处理程序中使用异步API

_btnAdd.Click += async (sender, args) => {
    string sUrl = "http://192.168.43.31/Service1.svc/insertIntoTableAdvertise";
    string sContentType = "application/json";

    JObject oJsonObject = new JObject();
    oJsonObject.Add("TxtGroup", _edtAdvGrouping.Text);
    oJsonObject.Add("TxtTitle", _edtTitle.Text);
    oJsonObject.Add("TxtDate", "0");
    oJsonObject.Add("TxtLocation","شاهین");
    oJsonObject.Add("TxtNumber", _edtNumber.Text);
    oJsonObject.Add("TxtPrice", _edtPrice.Text);
    oJsonObject.Add("TxtExpression", _edtExpression.Text);

    try {
        var content = new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType);

        var response = await httpClient.PostAsync(sUrl, content);

        var responseContent = await response.Content.ReadAsStringAsync();

        Toast.MakeText(this, responseContent, ToastLength.Short).Show();

    } catch (Exception ex) {
        Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
    }
}