Json通过httpclient mvvmcross发布

时间:2017-02-07 09:31:25

标签: c# json xamarin httpclient mvvmcross

Hy ya'll,

我在MVVMCROSS解决方案中通过HttpClient对象发送JSON POST时遇到问题(Xamarin)MVVMCROSS只是用于跨平台e.a的模型视图ViewModel框架。 Droid,iOS,Windows等。

所以解决方案是这样的:

 --Core (where I have my ViewModels and Services)
 --Droid (Android Layout etc)
 --iOS (Not used currently)

核心内部我有我的服务类,我通过IoC初始化(控制反转,类似依赖注入)

我有这个很棒的很酷的API,我可以通过JSON Post请求使用它。 API确实面对识别并发回面部的“情绪”(愤怒,中立,快乐等)

要使用此功能,我的JSON应该如下所示

{
    "url" : "http://previews.123rf.com/images/kadettmann/kadettmann1508/kadettmann150800099/43824672-Handsome-argentinian-guy-at-beach-Stock-Photo-happy.jpg"
}

到目前为止一切顺利,现在POST网址是:https://api.projectoxford.ai/emotion/v1.0/recognize我觉得似乎并不难!

我还需要发送两个标题:

Content-Type = application/json
Ocp-Apim-Subscription-Key = My super awesome secret key

如果通过POSTMAN(Chrome插件)发送此JSON,我会得到预期的结果:

[
  {
    "faceRectangle": {
      "height": 312,
      "left": 563,
      "top": 208,
      "width": 312
    },
    "scores": {
      "anger": 0.00000000112,
      "contempt": 0.000000049,
      "disgust": 0.0000000035,
      "fear": 0.000000000106,
      "happiness": 0.99999994,
      "neutral": 0.000000000238,
      "sadness": 0.00000000005,
      "surprise": 0.00000000160
    }
  }
]

所以现在我正在尝试为Android和iOS制作一个MVVMCROSS应用程序,它将此JSON发送到Microsoft的服务器。

我使用的方法如下:

public async Task<bool> RestRequestSucces(string secret, string jsonSerialized)
{
    bool result = false;    

    try
    {
        HttpResponseMessage response;

        using (var httpClient = new HttpClient())
        {
            var request = new StringContent(jsonSerialized);
            request.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", secret);

            response = await httpClient.PostAsync(new Uri("https://api.projectoxford.ai/emotion/v1.0/recognize"), request);

            result = true;
        }
    }
    catch (Exception e)
    {
        string error = e.Message;
        result = false;
    }
    return result;
}

要序列化的JsonObject如下所示:

public class URLObject
{
    public string url { get; set; }
}

要序列化我使用此对象的对象

private IMvxJsonConverter serializer = Mvx.Resolve<IMvxJsonConverter>();
serializer.SerializeObject(urlObject);

但在response = await httpClient.PostAsync我的代码挂了。它没有任何进一步的优势。

我像这样调用方法RestRequestSucces

IRestService restService = Mvx.Resolve<IRestService>();
restService.RestRequestSucces(secret, jsonSerialized);

这一切都发生在Core项目中。

我的AndroidManifest.xml如下所示:

...
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application android:label="@string/ApplicationName" android:icon="@drawable/Icon" android:theme="@style/MyTheme"></application>
</manifest>

如果有人能告诉我如何在CORE项目中通过MVVMCROSS发布一个'简单'的JSON,那就太棒了!

1 个答案:

答案 0 :(得分:1)

自己解决了,

结果HttpClient在某些TLS / SSL网站(https)上出现问题。只需使用ModernHttpClient解决了我的问题!

其余代码保持不变,只有HttpClient构造函数不同

using (var httpClient = new HttpClient(new NativeMessageHandler()))
{
    ....
}

NativeMessageHandlerHttpClientHandler,可以在ModernHttpClient中找到,代码如下:

namespace ModernHttpClient
{
    public class NativeMessageHandler : HttpClientHandler
    {
        public NativeMessageHandler();
        public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null);

        public bool DisableCaching { get; set; }

        public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback);
        [AsyncStateMachine(typeof(<SendAsync>c__async0))]
        [DebuggerStepThrough]
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
    }
}

希望你们能用到这个! 链接到github上的ModernHttpClient