在交换access_token的代码时出错400和415

时间:2017-02-04 16:29:40

标签: objective-c spotify

我正在编写一个应用程序来授权自己进入Spotify。我使用节点app.js示例来使事情正常工作,现在重新编写目标C.我通过回调函数提取了授权代码

{{1}}

然后我发布此请求并获取 {“error”:“server_error”,“error_description”:“意外状态:415”} 返回。

我发现有关此主题的各种问题围绕着需要应用的内容类型/ x-www-form-urlencoded,但这不是直接的解决方法。

有人对我有任何建议吗?

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案NSURLRequest : Post data and read the posted page

似乎HTTPBody中的原始数据需要采用不同的格式 - 根本没有JSON。以上链接有一个有用的功能,我稍微更新

- (NSData *)encodeDictionary:(NSDictionary *)dictionary {

NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {

    NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPasswordAllowedCharacterSet]];
    NSString *encodedKey = [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPasswordAllowedCharacterSet]];

    NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
    [parts addObject:part];
}

NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];

}

和..

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//NSLog(@"request.header %@", request.allHTTPHeaderFields.description);

// put in the body form using the new function
NSDictionary * parameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"authorization_code",@"grant_type",authorisationCode,@"code",redirectUri,@"redirect_uri", nil ];
NSData * requestBodyData = [self encodeDictionary:parameters];
request.HTTPBody = requestBodyData;