我正在使用以下代码将图像上传到我的服务器:
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
DataManager *manager = [DataManager sharedManager];
[_params setObject:[manager token] forKey:@"token"];
[_params setObject:[NSString stringWithFormat:@"%d",[manager site_id]] forKey:@"site"];
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = @"image";
NSURL* requestURL = [NSURL URLWithString:@"https://mysite.com/api/upload/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSData *imageData = UIImageJPEGRepresentation(saveImage, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSLog(@"%@",body);
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
NSLog(@"Sending request with length: %@",postLength);
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
在我尝试上传时查看我的服务器日志,我没有得到很多信息:
82.132.x.x - - [06/Feb/2013:15:37:45 +0000] "-" 400 0 "-" "-"
将此与来自同一应用程序的另一个查询进行比较:
82.132.x.x - - [06/Feb/2013:15:36:13 +0000] "GET /api/sites/?token=blah HTTP/1.1" 200 269 "-" "My%20App/1.0 CFNetwork/609.1.4 Darwin/13.0.0"
我怎样才能弄清楚出了什么问题?显然,请求在某种程度上是错误的,导致错误 400。有什么工具可以用来检查它吗?