在我的iOS应用中,我使用NSURLConnection将json字符串发布到服务器。

    post_string = @"{"function":"getHuddleDetails", "parameters": {"user_id": "167","location_id": "71","huddle_id": "328","checkin_id": "1287"},"token":""}"


  -(void)myServerRequests:(NSString *)post_string{


    NSData *postData = [post_string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://www.myServerURl.com/jsonpost"]];
    [request setTimeoutInterval:100];

    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        webData = [[NSMutableData alloc]init];
    }

   }

并使用NSURLSession使用以下代码发布 multipart / form-data (非JSON)
 -(void)myFunction:(NSString *)user_name paswd:(NSString *)pass_word {

   NSString *boundary = [self boundaryString];
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.myServerURl.com/formpost"]];
   [request setHTTPMethod:@"POST"];
   [request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];



   NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
   NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

   NSMutableData *postbody = [NSMutableData data];
  [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];




   [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@", user_name] dataUsingEncoding:NSUTF8StringEncoding]];
   [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@", pass_word] dataUsingEncoding:NSUTF8StringEncoding]];
   [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

   [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];




     NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSAssert(!error, @"%s: uploadTaskWithRequest error: %@", __FUNCTION__, error);


      NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;



    }];
    [task resume];
  }

这与NSURLSession完美配合,但是当我尝试发布json字符串(将其转换为NSDATA并使用NSURLSession进行发布)时,它无法正常工作。

为什么会发生?
提前致谢

最佳答案

如果要将JSON发送到服务器,则应将内容类型相应地设置为application/json,而您的内容实际上就是这样:JSON最好以UTF-8编码。

在方法myServerRequests:中,您设置了内容类型application/x-www-form-urlencoded-但未正确设置相应的内容。如何执行此操作可以在此处阅读:URL-encoded form data。此外,指定字符集参数完全无效。

如果要发送application/x-www-form-urlencoded内容类型的字符串参数,则也不应使用有损转换。而是使用UTF-8。请注意,NSStringlength返回UTF-16代码点的数量-这与UTF-8编码的字符串的字节数不同。

回顾:

请勿使用application / x-www-form-urlencoded内容类型。代替:
Content-Type = application/jsonContent-Length = <length in bytes of the UTF-8 encoded JSON>
解决这些问题后,请求应该可以。

当使用multipart / form-data请求时,我强烈建议使用网络库。手动执行此操作很容易出错,并且您至少需要阅读300 RFC才能知道您正确执行了此操作;)

07-28 02:54
查看更多