格式错误:将JSON数据添加到现有URL

时间:2013-07-25 13:17:34

标签: ios json post request

我需要发送这样的请求:

"http://api.site.com/login?q={"meta":{"api_key":"cb2f734a14ee3527b3"},"request":{"id":"username@host.name","password":"passw0rd"}}`

...响应应该是{"id":399205,"token":"d43f8b2fe37aa19ac7057701"}为此,我尝试了以下代码:

self.responseData = [NSMutableData data];
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:@"cb2f734a14ee3527b3" forKey:@"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:@"tc-d@gmail.com",@"id", @"abc",@"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, @"meta", idPasswordDict, @"request", nil];
NSURL *url = [NSURL URLWithString:@"http://api.site.com/login?="];
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
    self.recievedData = [NSMutableData data];
}

稍后,我接受以下内容:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.recievedData appendData:data];
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}

响应数据返回“<h1>CHttpException</h1><p>wrong sign</p>”据我所知,在这种情况下,将json数据添加到当前url的方式并不合适。有没有人就如何解决这个问题提出建议?

解决我的问题。将发布的json转换为附加字符串到基本url-string。这就是我做到的:

NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *dictString = [[NSMutableString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
[dictString insertString:@"http://api.site.com/login?q=" atIndex:0];

//don't know why but dictString contains a lot of @"\n" and spaces to present it nice-formated.
[dictString replaceOccurrencesOfString:@"\n" withString:@"" options:nil range:NSMakeRange(0, dictString.length)];
[dictString replaceOccurrencesOfString:@" " withString:@"" options:nil range:NSMakeRange(0, dictString.length)];
NSURL *url = [NSURL URLWithString:[dictString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

如果它有助于某人在此问题附近感谢嘀嗒=)

1 个答案:

答案 0 :(得分:0)

您可以使用AFNetworking库做到这一点 - 它易于实施和使用。在这种情况下,您需要的整个代码非常简单,而且对我来说总是很好。

NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:@"cb2f734a14ee3527b3" forKey:@"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:@"tc-d@gmail.com",@"id", @"abc",@"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, @"meta", idPasswordDict, @"request", nil];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSString *urlString = @"http://api.site.com/login";
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:jsonString, @"q", nil];
NSURL *url = [NSURL URLWithString:urlString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:nil parameters:parameters];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        //OK
        NSLog(@"%@", JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        //Response failed
    }];
    [operation start];