2013-07-31 2 views
0

JSON 응답을 받으려는 서버에 API가 있습니다. 몇 가지 요청 도구를 사용하여 호출을 시뮬레이트하고 매번 정확한 데이터를 가져 왔습니다. 내 요청 설정은 다음과 같습니다.iOS http POST 요청

NSString *post = [NSString stringWithFormat:@"user_id=%@&last_sync=%@",user_id, last_sync]; 
NSURL *directoryURL = [NSURL URLWithString:directoryURI]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:directoryURL]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:[NSData dataWithBytes:[post UTF8String] length:[post length]]]; 

콘텐츠 유형은 시뮬레이션 된 요청에서도 동일합니다. 반환 된 오류는 없으며 내용이 없습니다.

+0

'@ "USER_ID = % @ & last_sync = % @"'이이 – meda

+0

쿼리 문자열입니다 POST에 없습니다 변환하려면 문자열을 데이터로 변환하여 HTTPBody에 전달합니다. http://developer.apple.com/library/ios/#documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/WorkingWithHTTPAndHTTPSRequests/WorkingWithHTTPAndHTTPS Requests.html –

+0

JSON API를 가지고 있다면 헤더는 다음과 같이 보일 것입니다. [request setValue : @ "application/json"forHTTPHeaderField : @ "Accept"]; [request setValue : @ "application/json"forHTTPHeaderField : @ "Content-Type"]; ' – meda

답변

1

는 그것을 알아 냈다. 분명히, 시뮬레이터와 달리, NSMutableRequest는 POST 변수의 조합과 URL의 쿼리 문자열 변수를 사용할 때 맘에 들지 않습니다. 변수를 POST 본문으로 옮겼습니다. 이제 모든 것이 잘 작동합니다.

0

POST 메서드를 사용하는 경우 문자열을 NSData 형식으로 변환해야합니다.

희망이 도움이 될 것입니다.

+0

예제 코드에 있습니다. 해결책을 찾아 냈지만 답으로 쓸 때까지 기다려야합니다. 고맙습니다. –

1

나는 AFNetworking 라이브러리를 사용하는데, 이는 HTTP 통신에서 많은 고통을 겪습니다.

내 POST 호출 아래 라인을 따라 있습니다

NSURL *nsURL = [NSURL URLWithString:@"http://someurl.com"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsURL]; 

[request setHTTPMethod:@"POST"]; 
[request addValue:@"xxxx" forHTTPHeaderField:@"yyy"]; // for any header params you want to pass in 
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

// If you need to pass any JSOn data to your WS 
if (json != nil) [request setHTTPBody:json]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
success:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, id JSON) 
{ 
    ... 
} 
failure:^(NSURLRequest *returnedRequest, NSHTTPURLResponse *response, NSError *error, id JSON) 
{ 
     ... 
}]; 
0

URL 양식 매개 변수 인코딩 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3 JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; POST http://example.com/ Content-Type: application/json {"foo": "bar", "baz": [1,2,3]}