从 Cocoa 向 Tumblr 发送 POST 请求 [英] Sending a POST request from Cocoa to Tumblr

查看:26
本文介绍了从 Cocoa 向 Tumblr 发送 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段不起作用,我收到身份验证失败"的消息.来自服务器的响应.有什么想法吗?

This code snippet isn't working, I'm getting an "Authentication Failed." response from the server. Any ideas?

    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:%@
Tumblr Password:%@", _tumblrLogin, _tumblrPassword);

    [NSURLConnection connectionWithRequest:request delegate:self];

    [request release];

_tumblrLogin_tumblrPassword 都在我的代码中的其他地方通过 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding 运行.我的登录电子邮件的格式为address+test@test.com".直接登录到 tumblr 效果很好,但我想知道+"字符是否导致编码问题?它没有被逃脱.应该是吗?

Both _tumblrLogin and _tumblrPassword are run through stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding elsewhere in my code. My login email is of the form "address+test@test.com". It works just fine for logging in directly to tumblr, but I'm wondering if the "+" character is causing problems with the encoding? It's not being escaped. Should it be?

感谢 Martin 的建议,我现在使用 CFURLCreateStringByAddingPercentEscapes 来转义我的登录名和密码.我仍然遇到同样的问题,但我的身份验证失败.

Thanks to Martin's suggestion, I'm now using CFURLCreateStringByAddingPercentEscapes to escape my login and password. I'm still having the same issue, though, my Authentication is failing.

推荐答案

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

The problem is that you are not creating a proper HTTP POST request. A POST request requires a properly formatted multipart MIME-encoded body containing all the parameters you want to send to the server. You are trying to set the parameters as HTTP headers which won't work at all.

此代码将执行您想要的操作,尤其要注意创建有效多部分 MIME 字符串的 NSString 类别:

This code will do what you want, note especially the NSString categories that create a valid Multipart MIME string:

@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:@"--%@
Content-Disposition: form-data; name="%@"

%@
",[NSString MIMEBoundary],key,[dict objectForKey:key]];
    }
    [result appendFormat:@"
--%@--
",[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:%@
Tumblr Password:%@", _tumblrLogin, _tumblrPassword);
    [NSURLConnection connectionWithRequest:request delegate:self];
    [request release];
}
@end

这篇关于从 Cocoa 向 Tumblr 发送 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆