【问题标题】:how to pass json data as parameter in the http using AFNetworking如何使用 AFNetworking 在 http 中将 json 数据作为参数传递
【发布时间】:2016-02-11 05:43:35
【问题描述】:

嗨,我正在尝试将 json 请求传递给服务器。我为此使用了 api,我必须在我的 api 中传递 json 参数,但我不知道如何在 api 中传递 json 参数,我知道我正在使用 AFNetworking在我使用过的代码下面传递 json 参数。请帮我解决这个问题提前谢谢..

参数格式如下

 {
  "email" : "abc@gmail.com",
  "phone" : "1234567890",
  "password" : "aaa",
  "medium" : "Email",
  "name" : "abc",
  "uos" : "i"
}

代码:

services *srv=[[services alloc]init];

NSString *str=@"http://emailsending.in/setting_saver_api/";                    NSString *method=@"registration.php";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];

[dict setObject:self.txtName.text forKey:@"name"];
[dict setObject:self.txtEmail.text forKey:@"email"];
[dict setObject:self.txtphone.text forKey:@"phone"];
[dict setObject:self.txtPassword.text forKey:@"password"];
[dict setObject:@"Email" forKey:@"medium"];
[dict setObject:@"i" forKey:@"uos"];
NSString *jsonString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json string :%@",jsonString);
}

[srv postToURL:str withMethod:method andParams:jsonString completion:^(BOOL success, NSDictionary *responseObj)

 {
     NSLog(@"res :%@",responseObj);
     NSLog(@"%d",success);
     NSLog(@"Successfully..................");
}];

【问题讨论】:

  • 我不知道,但数据没有传递到服务器,但我得到了 json 格式的转换字符串,我将其作为参数传递,我得到的响应是状态 = 0 和 msg = 需要数据
  • github.com/AFNetworking/AFNetworking 在 github 上参考这个。你会发现 - JSON 参数编码。

标签: ios objective-c json web-services afnetworking


【解决方案1】:

以下代码可能会有所帮助:

NSString *comment_id = @"comment"
NSString *string = [NSString stringWithFormat:@"apiURL];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"apikey":apikey,@"text":text, @"comment_id":comment_id}; // this is an example 

[manager POST:string parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success %@", responseObject);
    NSDictionary *data = (NSDictionary *)responseObject;

    if ([[[data objectForKey:@"response"] objectForKey:@"status"] integerValue]){

        //success 

    }else{
        //else part goes here 
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

【讨论】:

  • 您好,我尝试了上面的代码,但收到错误 NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
  • 联系您的服务器端人员。
  • 你有问题吗?
【解决方案2】:

试试这个方法,

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];


    NSDictionary *params = @ {@"user" :txtUserName, @"pwd" :txtPwd };


    [manager POST:URL_SIGNIN parameters:params
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"JSON: %@", responseObject);
    }
    failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];

【讨论】:

  • 您好,您知道如何在浏览器或邮递员类型的api测试工具中测试这种类型的api吗?
  • file:///Users/rajeshvishnani/Desktop/Scr​​een%20Shot%202016-02-11%20at%2012.18.14%20PM.png 我有这样的测试 api 这是正确的json类型参数?
  • 我试试上面的代码,但我得到一个错误 NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
  • 把你的测试结果发给我
【解决方案3】:

这是你得到的错误。请联系您的后端团队。

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /setting_saver_api/ was not found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>

你可以这样使用:

NSString* jsonString = [NSString stringWithFormat:@"email=%@&phone=%@&password=%@&name=%@&uos=%@",email.text,phone.text,password.text,name.text,uos.text];//enter your own values

NSURL *urlPath = [NSURL URLWithString:@"Your URL String"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

 [request setHTTPMethod:@"POST"];
 [request setHTTPBody:requestData];
 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {            
                if(data != nil){
                  //your code
                }
                else {
                  //error
                }
}];

希望这会有所帮助。

【讨论】:

  • 您好,您知道如何在浏览器或邮递员类型的api测试工具中测试这种类型的api吗?
  • 是的@Birendra。我经常使用它们。你的问题解决了吗?
  • 一次,是的,最好的做法是这样做@Birendra。
  • 请给我你得到的答复?
  • 请给我你得到的答复?
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多