无法从 Iphone 生成 Json 请求正文

Posted

技术标签:

【中文标题】无法从 Iphone 生成 Json 请求正文【英文标题】:Could not make Json Request body from Iphone 【发布时间】:2012-07-06 18:12:12 【问题描述】:

我是一名 .Net 软件开发人员。我为用户验证创建了一个 WCF Rest API 以下是它的签名。

[OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/Validate", Method = "POST")]
    UserListResponse ValidateUser(Login obj);

在 fiddler 中运行良好,具有以下请求正文

"Username":"admin",Password:"111"

我的问题是,无法从 Iphone 使用 http post 方法访问它,但它在 android Http post 方法中运行良好。

以下是我的代码:

NSError *theError = nil;

NSArray *keys = [NSArray arrayWithObjects:@"Username", @"Password", nil];

NSArray *objects = [NSArray arrayWithObjects:@"admin", @"111", nil];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSString *myJSONString =[jsonDictionary JSONRepresentation];

NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"myJSONString :%@", myJSONString); 

NSLog(@"myJSONData :%@", myJSONData); 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.192/ShopMonkeyService/ShopMonkey.svc/Validate"]];

[request setHTTPBody:myJSONData]; 

[request setHTTPMethod:@"POST"];

NSURLResponse *theResponse =[[NSURLResponse alloc]init];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];   

NSLog(@"response : %@", theResponse);

NSLog(@"error : %@", theError);

NSLog(@"data : %@", data);

NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"string: %@", string);

NSDictionary *jsonDictionaryResponse = [string JSONValue];

NSLog(@"dic: %@", jsonDictionaryResponse);

以下是我的回复错误:

2012-07-06 11:49:04.201 ShopMonkey[524:207] -JSONRepresentation 失败的。错误跟踪是:(null)

2012-07-06 11:49:04.201 ShopMonkey[524:207] myJSONString :"密码":"111","用户名":"admin"

2012-07-06 11:49:04.201 ShopMonkey[524:207] myJSONData :

2012-07-06 11:51:13.312 ShopMonkey[524:207] 回复:(空)

2012-07-06 11:51:13.312 ShopMonkey[524:207] 错误:错误 Domain=NSURLErrorDomain Code=-1005 "网络连接丢失。" 用户信息=0x6041370 NSErrorFailingURLStringKey=http://192.168.1.192/ShopMonkeyService/ShopMonkey.svc/Validate, NSErrorFailingURLKey=http://192.168.1.192/ShopMonkeyService/ShopMonkey.svc/Validate, NSLocalizedDescription=网络连接丢失。, NSUnderlyingError=0x6043a90 "网络连接丢失。"

2012-07-06 11:51:13.312 ShopMonkey[524:207] 数据:(空)

2012-07-06 11:51:13.313 ShopMonkey[524:207] 字符串:

2012-07-06 11:51:13.313 ShopMonkey[524:207] -JSONValue 失败。错误 跟踪是:(

"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x6041b90 NSLocalizedDescription=Unexpected

字符串结束"

)

2012-07-06 11:51:13.313 ShopMonkey[524:207] dic: (null)

谁能指出我出了什么问题。

提前致谢 维杰

查看我的错误详情 vivek

错误详情:

2012-07-06 16:54:37.416 ShopMonkey[1895:40b] -[CJSONSerializer serializeDictionary:]:无法识别的选择器发送到实例 0x4c03740

2012-07-06 16:54:37.417 ShopMonkey[1895:40b] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[CJSONSerializer serializeDictionary:]:发送了无法识别的选择器到实例 0x4c03740'

* 首次抛出时调用堆栈:

(

0 CoreFoundation 0x00ec2be9 __exceptionPreprocess + 185

1 libobjc.A.dylib 0x010175c2 objc_exception_throw + 47

2 CoreFoundation 0x00ec46fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187

3 CoreFoundation 0x00e34366 转发 + 966

4 核心基础 0x00e33f22 _CF_forwarding_prep_0 + 50

5 ShopMonkey 0x000030c5 -[ShopMonkeyViewController signinbtnclick] + 425

6 UIKit 0x0034fa6e -[UIApplication sendAction:to:from:forEvent:] + 119

7 UIKit 0x003de1b5 -[UIControl sendAction:to:forEvent:] + 67

8 UIKit 0x003e0647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527

9 UIKit 0x003df1f4 -[UIControl touchesEnded:withEvent:] + 458

10 UIKit 0x003740d1 -[UIWindow _sendTouchesForEvent:] + 567

11 UIKit 0x0035537a -[UIApplication sendEvent:] + 447

12 UIKit 0x0035a732 _UIApplicationHandleEvent + 7576

13 图形服务 0x0177ca36 PurpleEventCallback + 1550

14 核心基础 0x00ea4064 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52

15 核心基础 0x00e046f7 __CFRunLoopDoSource1 + 215

16 核心基础 0x00e01983 __CFRunLoopRun + 979

17 CoreFoundation 0x00e01240 CFRunLoopRunSpecific + 208

18 CoreFoundation 0x00e01161 CFRunLoopRunInMode + 97

19 图形服务 0x0177b268 GSEventRunModal + 217

20 图形服务 0x0177b32d GSEventRun + 115

21 UIKit 0x0035e42e UIApplicationMain + 1160

22 ShopMonkey 0x000026d8 主 + 102

23 ShopMonkey 0x00002669 开始 + 53

)

在抛出 'NSException' 实例后调用终止

【问题讨论】:

【参考方案1】:

对于在 JSON 中按值传递的键,您应该朝这个方向发展 ..

    NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil];
NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];

[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(@"%@", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", theBodyData);
[theRequest setHTTPBody:theBodyData];

NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];
NSLog(@"%@", theResponseDictionary);
NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"];
[self setValue:theGreeting forKey:@"greeting"];

只是检查.. 还有一件事你会从这里找到这个文件 CJSONSerializer CJSONSerializer file path

..................

【讨论】:

嗨 vivek 我已经尝试过你的建议,但我收到以下错误请参考我的问题我已更新错误详细信息。 让你试试这个 url 传递参数,方法是在后面附加这样的“192.168.1.192/ShopMonkeyService/ShopMonkey.svc/…”..检查你得到什么响应..因为在日志中你得到空响应.. 感谢您的回复其余服务将不允许URL发布它应该仅通过制作Json数据并仅在HTTP请求正文中发布数据来完成。任何帮助将不胜感激... 同样的 API 也可以从 Android 访问,那里的 json 响应是成功的,只有在 iphone 中它不起作用。 vivek 有什么更新吗?【参考方案2】:
 NSURL *url = [NSURL URLWithString:@"http://alkjdlkjaflkdjflakjdf"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

NSString *req;

    req = [NSString stringWithFormat:@"username=%@&pass=%@",userName,Password];

[request setHTTPMethod:@"POST"];
[request setHTTPBody: [req dataUsingEncoding:NSISOLatin1StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];

if (connection) 
    receivedData = [[NSMutableData alloc]initWithLength:0]; // an ivar of type NSMutableData
 else 

    UIAlertView *failAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"Could Not Connect" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [failAlert show];

现在使用以下委托来处理请求

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data


    [receivedData appendData:data];




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

receivedData = nil;

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:[NSString stringWithFormat:@"%@",error.localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

    [self performSelector:@selector(getData:) withObject:receivedData afterDelay:0];


现在你必须解析上面调用的 getData 函数中的数据

-(void)getData:(NSData*)response
NSError *erro;

SBJSON *parse                               =           [[SBJSON alloc]init]; 
// have to include SBJSON lib else you can use the inbuild NSJSONSerialization

NSString *jsonString                        =           [[NSString alloc] initWithData:response
                                                                              encoding:NSUTF8StringEncoding]; 

NSDictionary *jsonData                      =           [parse objectWithString:jsonString error:&erro];
NSArray *allEvents                          =           [jsonData objectForKey:@"Your_OBJECT"];

  if(![allEvents isKindOfClass:[NSNull class]] && [allEvents count] > 0)
  

 // now do what you want with the data   

  

【讨论】:

你是否用你的改变了 url,并且还在 req 字符串中添加了参数,并且还在你的控制器中添加了一个 ivar NSMutbaleData *receivedData 也在行 [jsonData objectForKey:@"Your_OBJECT"];代替 Your_OBJECT 你必须用你想要数据的特定 json 键替换它

以上是关于无法从 Iphone 生成 Json 请求正文的主要内容,如果未能解决你的问题,请参考以下文章

无法解析请求正文。确保请求正文与指定的内容类型匹配:应用程序/json [重复]

Java - 从请求 JSON 生成 JWS/JWT

错误状态:无法设置内容类型为“application/json”的请求的正文字段

斜角 | CustomPOST:我无法发出 CORS POST 请求,正文中有 json 数据对象

AWS Lambda 错误:当 url 参数包含 JSON 数组时,“无法将请求正文解析为 json”

Ruby:带有 JSON 正文的 PUT 请求?