【问题标题】:Bad formatting: Add JSON data to existing URL格式错误:将 JSON 数据添加到现有 URL
【发布时间】:2013-07-25 13:17:33
【问题描述】:

我需要这样发送请求:

"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 字符串。我就是这样做的:

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

如果它对这个问题附近的人有帮助,将不胜感激=)

【问题讨论】:

  • 马上,您在顶部的示例显示的是 GET 而不是 POST。 GET 在 URL 中使用参数,POST 在消息正文中发送数据。
  • 您尝试为 URL 设置查询参数,但实际上并未设置任何参数。因此,错误响应(在 HTML 中)。您应该查阅 Web 服务的 API 文档。可能,您需要不同的 Content-Type。或者只是尝试省略部分查询字符串(两个字符“?=”)的 URL。
  • @KHansenSF 实际上,一个 POST 请求的 URL 中可能有查询参数——这在实践中很少这样做。 ;)
  • 那么如何将 json 格式的字符串添加到 url?我听说过一些 json 表示,但没有找到它=(它对我的问题有帮助吗?

标签: ios json post request


【解决方案1】:

您可以使用 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-10-02
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多