Xamarin:将HttpClient POST与动态类结合使用

时间:2015-03-05 21:38:26

标签: c# xamarin.ios xamarin json.net httpclient

我有一些需要相当复杂的对象的服务。每个服务使用几乎相同的基础对象,但需要为每个服务进行扩展。

一个简单的例子: 标准对象类似于:

ContextObject {
    params {
       Device {
          Name: "MyMobileDevice",
          ID: 123455691919238
       }
    }
}

对于我的服务,我需要在params下添加一些属性, 类似的东西:

ContextObject {
    params {
       Device {
          Name: "MyMobileDevice",
          ID: 123455691919238
       },
       requested_employee_id: 112929
    }
}

我尝试使用JObject来实现这一点,并且到目前为止它已经运行但现在我无法找到关于如何使用HttpClient将此对象发送到我的服务器的正确示例。

编辑: 这是我的完整JObject,所有请求都需要:

        public static JObject DefaultContext (string ServiceMethod) {
        var Context = new JObject();
        Context["version"] = "1.1";
        Context["method"] = ServiceMethod;
        Context["params"] = JObject.FromObject( new {
            Context = JObject.FromObject( new {
                User = App.UserSettings.USERNAME,
                Password = App.UserSettings.PASSWORD,
                SerialNumber = "1234567890", // TODO: use generated id
                Locale = "de-DE",
                Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffzzz"),

                Device = JObject.FromObject( new {
                    DeviceType = "phone",
                    ProductType = "D6603", // TODO: Get from Device-Info
                    screen = JObject.FromObject( new {
                        Density = "xxhdpi", // TODO: Get from Device-Info
                        resolution = JObject.FromObject( new {
                            Height = "1920", // TODO: Get from Device-Info
                            Width = "1080" // TODO: Get from Device-Info
                        })
                    }),
                    version = JObject.FromObject( new {
                        AppVersion = "myAppVersion", // TODO: Get App-Information                           LayoutVersion = "1.0"
                    } )
                })
            })
        });

        return mobileContext;
    }

对于我的请求,我需要在“params”-Node下添加参数。适用于:

mobileContext["params"]["mynewparameter"] = "FOO";

现在我想通过System.Net.Http-Client将这个JObject发送到我的服务器上,如下所示:

var client = new HttpClient ();
client.BaseAddress = new Uri (App.UserSettings.HOST + ":" + App.UserSettings.PORT + App.UserSettings.TYPE);
client.Timeout = 3000;      

var context = MyContext.DefaultContext (ServiceMethods.CUSTOMER_LIST_METHOD);   
context ["params"] ["myrequestparam"] = "FOO";
var jsonString = JsonConvert.SerializeObject (context);
var responseData = await client.Get???????

我的一般方法是否正确?你会怎么做?有关于如何处理这些动态内容的示例吗? 我找不到一个关于如何正确使用httpclient的例子和Newtonsoft.JSON-Library我实际工作的代码有多远?

0 个答案:

没有答案