2010-12-11 35 views
1

我正在嘗試利用http POST來發送JSON對象(UIImage包含在POST中)。以下是我目前使用的代碼,但由於某些原因服務器未收到POST。任何人都可以提供洞察力,爲什麼這可能不工作?對於UIImage使用JSON的HTTP POST

NSString *userString = [[NSString alloc]init]; 
userString = [[NSUserDefaults standardUserDefaults]valueForKey:@"userId"]; 

//convert image to nsdata object 
NSData *imageData = UIImageJPEGRepresentation(imageView.image, .9); 

NSLog(@"User id is:%@", userString); 
NSLog(@"The tag string:%@", myTagString); 
NSLog(@"the question string is:%@", myQuestionString); 
NSLog(@"the image data is:%@", imageData); 
NSArray *keys = [NSArray arrayWithObjects:@"category", @"question", @"latitude", @"longitude", @"user_id", @"image",nil]; 

NSArray *objects = [NSArray arrayWithObjects:myTagString, myQuestionString, @"0.0", @"0.0", userString, imageData, nil]; 
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

NSURL *theURL = [NSURL URLWithString:@"http://theserver.com/query"]; 
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f]; 
[theRequest setHTTPMethod:@"POST"]; 

[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"]; 
NSString *theBodyString = [[NSString alloc]init]; 
theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary]; 
NSLog(@"body string: %@", theBodyString); 
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding]; 
NSLog(@"body data: %@", theBodyData); 
[theRequest setHTTPBody:theBodyData]; 

NSURLResponse *theResponse = NULL; 
NSError *theError = NULL; 
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError]; 
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease]; 
NSLog(@"the response string:%@", theResponseString); 
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseData error:nil]; 
NSLog(@"%@", theResponseDictionary); 

這是我在論壇中的第一篇文章,所以如果某些格式錯誤,我很抱歉。隨意批評它,以便我可以在將來提交更好的帖子。

回答

0

看看Github http://akos.ma/7qp這個項目中的代碼,其中Wrapper類在請求中設置了一對頭文件,以便服務器可以處理上傳的二進制數據。查看第118行中的uploadData:toUrl:方法,該方法設置所需的內容類型標題。