POST请求授权标头

时间:2016-02-18 11:01:39

标签: ios objective-c post mailchimp

我在发送POST请求以将用户订阅到MailChimp列表时遇到一些问题。这是我到目前为止所得到的:

    NSString *Post = [[NSString alloc] initWithFormat:@"{email_address:%@, status:pending}",email];
    NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSURL *url = [NSURL URLWithString:@"https://us10.api.mailchimp.com/3.0/lists/124709/members/"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    [req addValue:@"apikey:*****************" forHTTPHeaderField: @"Authorisation"];
    [req addValue:@"application/json" forHTTPHeaderField: @"content-type"];
    [req setHTTPBody:PostData];

    NSData *res = [NSURLConnection  sendSynchronousRequest:req returningResponse:NULL error:NULL];
    NSString *myString = [[NSString alloc] initWithData:res encoding:NSUTF8StringEncoding];
    NSLog(@"%@", myString);

但每次我收到回复说#34;您的请求不包含API密钥。"。我显然隐藏了我的钥匙,但它绝对是一个有效的钥匙,所以这不是问题所在。我关注以下curl请求代码:

curl --request POST \
--url 'https://usX.api.mailchimp.com/3.0/lists/57afe96172/members' \
--user 'anystring:apikey' \
--header 'content-type: application/json' \
--data '{"email_address":"urist.mcvankab+3@freddiesjokes.com", "status":"subscribed"}' \
--include

非常感谢任何帮助:)

3 个答案:

答案 0 :(得分:0)

试试这个,我这样做了

[request setValue@"apikey:*****************" forHTTPHeaderField: "Authorisation"];

答案 1 :(得分:0)

试试这个

NSString *Post = [[NSString alloc] initWithFormat:@"{email_address:%@, status:pending}",email];

    NSURL *url = [NSURL URLWithString:@"https://us10.api.mailchimp.com/3.0/lists/124709/members/"];    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:10];
    [request setHTTPMethod:"POST"];
    [request setValue:"YOUR_KEY" forHTTPHeaderField:@"Authorisation"];
    [request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: [Post dataUsingEncoding:NSUTF8StringEncoding]];

    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
              if (responseObject)
              {                        
              }
              } failure:^(AFHTTPRequestOperation *operation, NSError *error){
               }];
              [op start];

希望这能帮到你

答案 2 :(得分:0)

不确定这是否是您问题的原因,但我认为您拼错了Authorization。它也应该是Content-Type