0

I need to send request like this:

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

...the response to which should look like {"id":399205,"token":"d43f8b2fe37aa19ac7057701"} To do so, I have tried the following code:

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];
}

Later on, I get in the following:

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

The response data comes back as "<h1>CHttpException</h1><p>wrong sign</p>" As I understand, the way of adding json data to the current url is not appropriate in this case. Does anyone have advice on how I can fix this?

resolve my problem. Convert posted json to appended string to base url-string. that's how I did it:

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]];

if it helps someone will appreciate tick near this issue=)

4

1 回答 1

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];
于 2013-07-25T22:19:11.067 回答