IBM MobileFirst 将 JSON 正文从 iOS SDK 发送到 Java 适配器

Posted

技术标签:

【中文标题】IBM MobileFirst 将 JSON 正文从 iOS SDK 发送到 Java 适配器【英文标题】:IBM MobileFirst Sending JSON Body from iOS SDK to Java Adapter 【发布时间】:2016-04-20 02:38:03 【问题描述】:

使用 IBM Mobile First Platform 7.1 版我正在尝试使用以下代码从 ios 应用程序调用 Java 适配器。

    [[WLResourceRequest requestWithURL:url method:WLHttpMethodPost] sendWithJSON:@@"one":@"two" completionHandler:^(WLResponse *response, NSError *error) 

    NSLog(@"%@",response);
    NSLog(@"%@",error);

    ];

适配器端的Java方法如下所示。

@POST
@Consumes("application/json")
@Produces("application/json")
public String hello(JSONObject body)
    return body.toString();

但我得到以下响应错误

2016-04-20 11:31:15.520 mbs-call[15092:3787968] 错误域=com.alamofire.error.serialization.response Code=-1011“请求失败:不支持的媒体类型 (415)”UserInfo= com.alamofire.serialization.response.error.response= URL: http:/0.0.0.0:10080/mbs-api/adapters/basicadpt/users 状态码: 415, headers 连接=关闭; "内容语言" = "en-US"; “内容长度”= 0; 日期 =“格林威治标准时间 2016 年 4 月 20 日星期三 02:31:15”; "X-Powered-By" = "Servlet/3.0"; , NSErrorFailingURLKey=http://0.0.0.0:10080/mbs-api/adapters/basicadpt/users, com.alamofire.serialization.response.error.data=, NSLocalizedDescription=请求失败:不支持的媒体类型 (415)

似乎在 iOS SDK 中,当调用任何方法时,它会在请求中添加标头 application/x-www-url-form-urlencoded

我有以下 2 个问题。

    如何将 JSON 正文传递给 Java 适配器? sendWithJSON 的行为在 iOS 和 android 上是不同的。在 Android 上,当我们调用适配器时,它似乎添加了 application/json 标头。这是错误还是行为的一部分?

【问题讨论】:

【参考方案1】:

我相信这是一个错误。我认为使用sendWithJSON 应该自动假定内容类型是application/json

我建议您提出支持请求 (PMR),以便他们改善体验。

与此同时,我找到了一个简单的解决方法:

[request addHeaderValue:@"application/json" forName:@"Content-Type"]

或者在 Swift 中:

request.addHeaderValue("application/json", forName: "Content-Type")

【讨论】:

【参考方案2】:

cordova 版本的应用程序也有同样的问题。

var userIDTag = 'some_string';  
var subTag = [userIDTag]; //<- this worked
var subTag = userIDTag; //<- this failed with the above error
var subTag = '[\'' + some_string + '\']'; //<- this also failed with the above error

以下是我最终为 Cordova 应用程序所做的工作。

function subscribeByTag(userIDTag) 
    var subTag = [userIDTag];
    console.log("subTag: " + subTag);
    WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
        MFPPush.subscribe(
            subTag,
            function(subTag) 
                navigator.notification.alert("Subscribed successfully");
            ,
            function(failureResponse)
                navigator.notification.alert("Failed to subscribe");
                console.log("Failedtosubscribe:" + JSON.stringify(failureResponse));
            
        )
    );

【讨论】:

以上是关于IBM MobileFirst 将 JSON 正文从 iOS SDK 发送到 Java 适配器的主要内容,如果未能解决你的问题,请参考以下文章

IBM MobileFirst/Worklight JSON

IBM Mobilefirst JAVA 适配器:访问 JSON 文件并从中读取内容

IBM MobileFirst:在命令行构建期间使用外部 jar 文件

IBM Mobilefirst Pugin 不支持 Cordova 版本 >7

将 Android 环境添加到 IBM MobileFirst Shell 组件

IBM Mobilefirst 和 IBM Bluemix