【问题标题】:how to create json object and set it in a post body in ios using asi http request如何使用 asi http 请求创建 json 对象并将其设置在 ios 的帖子正文中
【发布时间】:2014-10-08 23:15:57
【问题描述】:
NSString *loginurl =[NSString
                     stringWithFormat:@"/ajax/useraccount.aspx/methodname"]
NSURL *url = [NSURL URLWithString:loginPath];

NSString *loginPath = [NSString stringWithFormat:@"%@%@",singleton.website,loginurl];

asiRequest = [[ASIHTTPRequest requestWithURL:url] retain];
[asiRequest addRequestHeader:@"Content-Type" value:@"application/json"];
[asiRequest addRequestHeader:@"Accept" value:@"application/json"];
[asiRequest setRequestMethod:@"POST"];

NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     @"email", @"Email",
                     @"fname", @"FirstName", nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSLog(@"this is value %@",postdata);
NSMutableData *mutablePostData = [NSMutableData dataWithData:postdata];


[asiRequest setPostBody:mutablePostData];
[asiRequest setDelegate:self];
[asiRequest setTimeOutSeconds:60];
[asiRequest startAsynchronous];
[activityIndicator startAnimating];

我想创建这种类型的对象并将其设置在帖子正文中 {"objectRequest":{"email":"Email","fname":"FirstName"}}

我无法点击该方法是我遗漏了什么还是有另一种方法来创建这种类型的 json 对象并将其设置在帖子正文中提前谢谢你

【问题讨论】:

  • 您不需要对象上的键周围的“”。你应该只使用 {objectRequest:{email:"Email",fname:"FirstName"}}
  • 我也试过这个,但没有工作,即 NSString *jsonRequest = [NSString stringWithFormat:@"{\registartionrequest:{\"Email\":\"%@\",\"名字\":\"%@\"}}",@"test",@"test"]; NSLog(@"请求:%@", jsonRequest); NSData *postData =[[NSStringstringWithFormat:@"%@",jsonRequest] dataUsingEncoding:NSUTF8StringEncoding];

标签: ios


【解决方案1】:

如果您愿意,您真的可以将该字符串作为正文返回。但是您必须将内容类型设置为"application/json"。其中一篇文章可能有助于在 ios 上执行此操作?

How to set content-type when using initWithContentsOfUrl

JSON file set content type to application/json AFNetworking

setting content-type overwriting httpbody?

【讨论】:

  • 我已经将其内容类型设置为 application/json [asiRequest addRequestHeader:@"Content-Type" value:@"application/json"]; [asiRequest addRequestHeader:@"Accept" value:@"application/json"];
【解决方案2】:

除了您忘记调用buildPostBody 方法外,您的代码一切正常。设置所有身体数据后,您必须调用此方法。

[asiRequest buildPostBody];
[asiRequest startAsynchronous];

如果这是一个新项目,我强烈建议使用任何其他最新的库。开发人员很久以前就停止了 ASIHTTPRequest 的开发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多