使用媒体和OAuth1更新Twitter状态

时间:2013-07-04 15:23:21

标签: ios rest twitter twitter-oauth multipartform-data

我正在尝试使用媒体更新身份验证用户的状态。 POST请求现在没有媒体工作。所以我得出结论,多部分数据图像有问题。这是代码:

    //image 
    NSData *imageData = UIImagePNGRepresentation(img);

    NSString *boundary = @"0246824681357ACXZabcxyz";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    // status
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"status\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",allParameters[@"status"]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    // media
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media[]\"; filename=\"1.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    //[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData  dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    NSLog(@"body = %@", [[NSString alloc] initWithData:body encoding:NSASCIIStringEncoding]);
    //END image

正文打印出以下内容:

--0246824681357ACXZabcxyz



Content-Disposition: form-data; name="status"



yoo

--0246824681357ACXZabcxyz

Content-Disposition: form-data; name="media[]"; filename="1.png"

Content-Type: application/octet-stream



PNG

我必须用ASCII编码,因为当我用UTF8编码时,NSString返回nil。我注意到这里没有打印关闭边界,这似乎很奇怪,但可能是因为ASCII编码?

这是我得到的回复:

2013-07-04 17:10:54.917 MyApp[662:60b] <NSHTTPURLResponse: 0x167335d0> { URL: https://api.twitter.com/1.1/statuses/update.json?status=yoo } { status code: 502, headers {
    "Accept-Ranges" = bytes;
    "Content-Encoding" = gzip;
    "Content-Length" = 1353;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Thu, 04 Jul 2013 15:09:58 GMT";
    "Last-Modified" = "Fri, 28 Jun 2013 19:39:00 GMT";
    Server = tfe;
    "Strict-Transport-Security" = "max-age=631138519";
    Vary = "Accept-Encoding";
    "x-pad" = "avoid browser bug";
    "x-xss-protection" = "1; mode=block";
} }

0 个答案:

没有答案