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