【问题标题】:HTTP Post using JSON for UIImage对 UIImage 使用 JSON 的 HTTP Post
【发布时间】:2010-12-11 19:32:27
【问题描述】:

我正在尝试利用 http POST 发送 JSON 对象(UIImage 包含在 POST 中)。下面是我目前正在使用的代码,但由于某种原因,服务器没有收到 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);

这是我在论坛上的第一篇文章,如果格式有误,我深表歉意。随时批评它,以便我将来提交更好的帖子。

【问题讨论】:

    标签: iphone objective-c json http-post


    【解决方案1】:

    看看我在 Github http://akos.ma/7qp 的这个项目中的代码,其中 Wrapper 类在请求中设置了几个标头,以便服务器可以处理正在上传的二进制数据。查看第 118 行的 uploadData:toUrl: 方法,该方法设置了所需的内容类型标头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2012-04-12
      相关资源
      最近更新 更多