2014-11-19 2 views
2

내 iOS 앱에서 json 문자열을 NSURLConnection을 사용하여 서버에 게시하고 있습니다.NSURLSession의 POST 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 완벽하게 잘 작동하지만 내가 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을 사용하여 게시 한 경우) 작동하지 않습니다.

왜 그런가? 미리 감사드립니다.

+0

"작동하지 않는 것"보다 잘해야합니다. 보고 된 오류, 잘못된 데이터를 얻었습니까? 서버에 대한 정보를 얻었습니까? 우리에게 더 많은 것들을 말해. –

답변

1

JSON을 서버로 보내려면 내용 유형을 application/json으로 설정해야하며 내용은 실제로는 JSON이 UTF-8로 인코딩되는 것이 좋습니다.

myServerRequests: 메서드에서 콘텐츠 형식을 application/x-www-form-urlencoded으로 설정했는데 해당 콘텐츠를 올바르게 설정하지 않았습니다. 이렇게하는 방법은 여기에서 읽을 수 있습니다 : URL-encoded form data. 또한 charset 매개 변수를 지정해도 아무런 효과가 없습니다.

콘텐츠 형식이 application/x-www-form-urlencoded 인 문자열 매개 변수를 보내려는 경우 손실 변환을 사용하지 않아야합니다. 대신 UTF-8을 사용하십시오. NSStringlength은 UTF-8 코드화 된 문자열의 바이트 수와 다른 UTF-16 코드 포인트의 수를 반환합니다.

요점을 되풀이하다 :

사용하지 마십시오을 application/x-www-form-urlencode되고 내용 유형입니다. 대신 :이 문제를 해결하면

Content-Type = application/json

Content-Length = <length in bytes of the UTF-8 encoded JSON>

, 요청이 확인되어야한다.

멀티 파트/폼 데이터 요청을 사용할 때 네트워크 라이브러리를 사용하는 것이 좋습니다. 이 작업을 직접하는 것은 오류가 발생하기 쉽고 제대로 수행하고 있음을 알기 위해서는 적어도 300 개의 RFC를 읽어야합니다.)