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);
这是我在论坛中的第一篇文章,所以如果某些格式错误,我很抱歉。随意批评它,以便我可以在将来提交更好的帖子。