我正在尝试使用媒体更新身份验证用户的状态。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";
} }