0

我想使用 JSON 和图像数据向服务器发送 POST 请求。我正在使用下面的代码,但每次运行时都会出现以下错误 -

{ 代码 = 400; Detail = "无法解析 form.request 中的 JSON"; 响应 = 错误;}

这是 ASIFormDataRequest 请求 -

ASIFormDataRequest *asiRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlForAPI]];
[asiRequest setTimeOutSeconds:60];

NSDictionary *dict1 = [[[NSDictionary alloc]initWithObjectsAndKeys:api_username,@"api_username",api_password,@"api_password",@"updateUser",@"method", nil] autorelease];
NSDictionary *dict2 = [[[NSDictionary alloc]initWithObjectsAndKeys:@"13",@"id",nil] autorelease];
NSDictionary *data = [[[NSDictionary alloc]initWithObjectsAndKeys:dict1,@"request",dict2,@"methodparam", nil] autorelease];

NSMutableDictionary *requestheaders =[[[NSMutableDictionary alloc]init] autorelease];
[requestheaders setValue:@"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY-8522EA03-7EA6-446F-9CAB-6EC10511FD22" forKey:@"Content-Type"];
[asiRequest setRequestHeaders:requestheaders];

NSData *jsonData = [data JSONData];
NSString *string = [[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
[asiRequest setRequestHeaders:requestheaders];

NSString *jsonString = [NSString stringWithFormat:@"REQUEST=%@",string];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString length]];

[asiRequest setPostBody:[NSMutableData dataWithData:requestData]];
[asiRequest addData:imageData forKey:@"logo"];

[asiRequest setShouldContinueWhenAppEntersBackground:YES];
[asiRequest setDelegate:self];
[asiRequest setRequestMethod:@"POST"];
[asiRequest setDidFailSelector:@selector(uploadFailed:)];
[asiRequest setDidFinishSelector:@selector(uploadFinished:)];
[asiRequest startAsynchronous];

如果你知道我哪里错了,请告诉我。任何建议将不胜感激。

4

1 回答 1

0

尝试如下,除此之外不需要做任何事情。

NSURL *url = [NSURL URLWithString:@"YOUR_URL_TO_POST"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request setData:imageData withFileName:@"img.png" andContentType:@"image/png" forKey:@"logo"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(uploadRequestFinished:)];
[request setDidFailSelector:@selector(uploadRequestFailed:)];
[request startAsynchronous];

并编写委托方法,例如,

- (void)uploadRequestFinished:(ASIHTTPRequest *)request{    

     NSString *responseString = [request responseString];
     NSLog( @"response--%@",responseString );

 }
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{

  NSLog(@" Error - Statistics file upload failed: \"%@\"",[[request error]   localizedDescription]);

  }
于 2013-04-03T12:14:57.307 回答