ios http请求发送json格式

时间:2012-11-14 13:39:54

标签: ios json http

我正在尝试使用以下参数调用Web服务:

{"Class":"Authorization","method":"login","user":"","pass":""}

如下

NSString *user = [NSString stringWithFormat:@"username=%@",_username.text];
NSString *pass = [NSString stringWithFormat:@"password=%@",_password.text];
NSString *Class = @"Authorization";
NSString *method = @"login";

//NSString *post = [NSString stringWithFormat:@"%@&%@&%@&%@", user, pass, Class, method ];

NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"Class\":"
                              "\"%@\""
                              ",\"method\":"
                              "\"%@\""
                              ",\"pass\":"
                              "\"%@\""
                              ",\"user\":"
                              "\"%@\""
                              "}'",
                              [Class stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [method stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [pass stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [user stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:180.0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded"   forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                          dataUsingEncoding:NSUTF8StringEncoding
                          allowLossyConversion:YES]];

    [request setHTTPBody:postData];

    NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
    [request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
    if (! error) {
        NSLog(@"%@",jsonDict);
    }else{
        NSLog(@"%@",error.localizedDescription);
    } 

每次结果都是:

  

由于未捕获的异常而终止应用   'NSInvalidArgumentException',原因:'data parameter is nil'

网络服务有:

  

input-content-type:text / json

     

output-content-type:text / json

任何帮助或示例都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我没有使用以下代码获得任何异常(但显然我无法访问您的服务器,所以我无法端到端地测试它):

NSDictionary *dictionary = @{
    @"Class"  : @"Authorization",
    @"method" : @"login",
    @"pass"   : _password.text,
    @"user"   : _username.text
};

NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:0
                                                     error:&error];
if (error)
    NSLog(@"Failure to serialize JSON object %@", error);

NSURL *url = [NSURL URLWithString:@"http://212.119.87.45:8080/IktissabServices/index.php/service"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];    
[request setHTTPBody:postData];

NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s sendSynchronousRequest error %@", __FUNCTION__, error);

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
if (!error) {
    NSLog(@"%@",jsonDict);
} else {
    NSLog(@"%s JSONObjectWithData error %@", __FUNCTION__, error);
} 

或者,如果您没有使用最新的Xcode并且无法访问字典的Modern Objective C定义,您显然可以用传统方式定义字典:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Authorization", @"Class",
                            @"login",         @"method",
                            _password.text,   @"pass",
                            _username.text,   @"user",
                            nil];

修改

jsonPostBody推断,字典条目可能需要:

NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : _password.text,
        @"user"   : _username.text
    }
};

或可能(但更不可能),从您的userpass定义推断:

NSDictionary *dictionary = @{
    @"json" : @{
        @"Class"  : @"Authorization",
        @"method" : @"login",
        @"pass"   : [NSString stringWithFormat:@"password=%@",_password.text],
        @"user"   : [NSString stringWithFormat:@"username=%@",_username.text]
    }
};

这是一个如何为您的服务器格式化JSON的问题。