2010-02-24 113 views
7

此代码段不起作用,我得到“身份验证失败”。来自服务器的响应。有任何想法吗?从Cocoa发送POST请求到Tumblr

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
            initWithURL: 
            [NSURL URLWithString:@"http://www.tumblr.com/api/write"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request addValue:_tumblrLogin forHTTPHeaderField:@"email"]; 
    [request addValue:_tumblrPassword forHTTPHeaderField:@"password"]; 
    [request addValue:@"regular" forHTTPHeaderField:@"type"]; 
    [request addValue:@"theTitle" forHTTPHeaderField:@"title"]; 
    [request addValue:@"theBody" forHTTPHeaderField:@"body"]; 

    NSLog(@"Tumblr Login:%@\nTumblr Password:%@", _tumblrLogin, _tumblrPassword); 

    [NSURLConnection connectionWithRequest:request delegate:self]; 

    [request release]; 

两个_tumblrLogin_tumblrPassword通过stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding其他地方在我的代码运行。我的登录电子邮件格式为“[email protected]”。它可以直接登录到tumblr,但是我想知道“+”字符是否会导致编码问题?它没有被转义。它应该是?


由于马丁的建议,我现在使用CFURLCreateStringByAddingPercentEscapes逃脱我的登录名和密码。我仍然有同样的问题,但是,我的身份验证失败。

+0

你能告诉我供的tumblr API的工作代码参考? – AppAspect 2011-07-14 10:43:28

回答

22

问题是您没有创建正确的HTTP POST请求。 POST请求需要格式正确的多部分MIME编码主体,其中包含要发送到服务器的所有参数。您正在尝试将参数设置为根本不起作用的HTTP标头。

该代码会做你想要什么,尤其要注意NSString类别创建一个有效的多部分MIME字符串:

@interface NSString (MIMEAdditions) 
+ (NSString*)MIMEBoundary; 
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict; 
@end 

@implementation NSString (MIMEAdditions) 
//this returns a unique boundary which is used in constructing the multipart MIME body of the POST request 
+ (NSString*)MIMEBoundary 
{ 
    static NSString* MIMEBoundary = nil; 
    if(!MIMEBoundary) 
     MIMEBoundary = [[NSString alloc] initWithFormat:@"----_=_YourAppNameNoSpaces_%@_=_----",[[NSProcessInfo processInfo] globallyUniqueString]]; 
    return MIMEBoundary; 
} 
//this create a correctly structured multipart MIME body for the POST request from a dictionary 
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict 
{ 
    NSMutableString* result = [NSMutableString string]; 
    for (NSString* key in dict) 
    { 
     [result appendFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",[NSString MIMEBoundary],key,[dict objectForKey:key]]; 
    } 
    [result appendFormat:@"\r\n--%@--\r\n",[NSString MIMEBoundary]]; 
    return result; 
} 
@end 


@implementation YourObject 
- (void)postToTumblr 
{ 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
            initWithURL: 
            [NSURL URLWithString:@"http://www.tumblr.com/api/write"]]; 
    [request setHTTPMethod:@"POST"]; 
    //tell the server to expect 8-bit encoded content as we're sending UTF-8 data, 
    //and UTF-8 is an 8-bit encoding 
    [request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"]; 
    //set the content-type header to multipart MIME 
    [request addValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@",[NSString MIMEBoundary]] forHTTPHeaderField: @"Content-Type"]; 

    //create a dictionary for all the fields you want to send in the POST request 
    NSDictionary* postData = [NSDictionary dictionaryWithObjectsAndKeys: 
           _tumblrLogin, @"email", 
           _tumblrPassword, @"password", 
           @"regular", @"type", 
           @"theTitle", @"title", 
           @"theBody", @"body", 
           nil]; 
    //set the body of the POST request to the multipart MIME encoded dictionary 
    [request setHTTPBody: [[NSString multipartMIMEStringWithDictionary: postData] dataUsingEncoding: NSUTF8StringEncoding]]; 
    NSLog(@"Tumblr Login:%@\nTumblr Password:%@", _tumblrLogin, _tumblrPassword); 
    [NSURLConnection connectionWithRequest:request delegate:self]; 
    [request release]; 
} 
@end 
+1

圣洁的废话。如果可以的话,我会将这个10000x出现。谢谢你的帮助。虽然我已经找到了你,但是你碰巧有链接解释headerFields(为什么需要设置8位编码)和MIMEBoundary? – kubi 2010-02-24 23:41:30

+0

您需要设置8位编码,因为请求的主体是使用UTF8编码的数据(使用'NSString'的'-dataUsingEncoding:'方法并传递'NSUTF8StringEncoding')。 UTF8是一种8位编码,如果它被解释为7位编码(ASCII),则会发生数据损坏。多部分MIME编码允许您创建包含单独部分的字符串。每个部分由用作边界标记的常量字符串划定。边界字符串是完全任意的,但不能包含在字符串的非边界内容中。 – 2010-02-25 00:12:26

+0

有关MIME的维基百科文章可能很有用:http://en.wikipedia.org/wiki/MIME#Multipart_messages – 2010-02-25 00:13:29

0

根据对this question的回答,stringByAddingPercentEscapesUsingEncoding:不会执行完整的转义编码。无论出于何种原因,这种方法的CoreFoundation版本确实,但是:

[(NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, 
    (CFStringRef)[[self mutableCopy] autorelease], NULL, 
    CFSTR("=,!$&'()*+;@?\n\"<>#\t :/"), kCFStringEncodingUTF8) autorelease]; 

您还可以使用的NSMutableString的replaceOccurencesOfString:withString:options:方法做手工更换,但该方法是多重复和繁琐。 (See here。)

+0

谢谢你。我确实使用了CFURLCreate ...按照你的建议,但它仍然不起作用。 – kubi 2010-02-24 17:31:37