2011-08-31 7 views
2

안녕하세요, 저는 웹 서비스에 HTTP POST 연결을 만드는 데 도움이 필요합니다. 나는 그것을하는 방법에 전혀 몰라요.HTTP POST JSON 메서드

URL의 일부로 필요한 입력 매개 변수를 전달할 때만 NSURLConnection을 만들었습니다. 이제는 웹 사이트와 JSON 본문을 제공하는 것만 큼 다른 것처럼 보입니다.

{ 
"lastmodified":"String content", 
"passengerId":9223372036854775807, 
"password":"String content", 
"userId":"String content" 
} 

누구든지이 문제에 대해 의견을 개진 할 수 있습니까? 웹 사이트가 www.myURL/operations/AddItem.com이라고 가정하십시오.

EDIT - 여기에 무슨 문제가 있습니까? 나는이 짧은 일부 값을 통과 있기 때문에

NSError *theError = nil; 
NSArray *keys = [NSArray arrayWithObjects:@"userId", @"password", nil]; 
NSArray *objects = [NSArray arrayWithObjects:userNameTextField.text, passwordTextField.text, nil]; 
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

NSString *myJSONString =[jsonDictionary JSONRepresentation]; 
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding]; 
NSLog(@"myJSONString :%@", myJSONString); 
NSLog(@"myJSONData :%@", myJSONData); 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://153.20.32.74/11AprP306/passenger/item"]]; 
[request setHTTPBody:myJSONData]; 
[request setHTTPMethod:@"POST"]; 

NSURLResponse *theResponse =[[NSURLResponse alloc]init]; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError]; 
NSLog(@"response : %@", theResponse); 
NSLog(@"error : %@", theError); 
NSLog(@"data : %@", data); 
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
NSLog(@"string: %@", string); 
NSDictionary *jsonDictionaryResponse = [string JSONValue]; 
NSLog(@"dic: %@", jsonDictionaryResponse); 
[string release]; 
[theResponse release]; 

내가 string: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Request Error</title> <style>BODY {..... 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'.

읽고있다가 (& passengerId을 LASTMODIFIED)? 이 요청이 새 계정을 만들 때만이 두 매개 변수가 필요한 이유는 모르겠습니다.

+2

['ASIHTTPRequest'] (http://allseeing-i.com/ASIHTTPRequest). 'appendPostData :'또는'appendPostDataFromFile :'메소드를 사용하여 JSON dict을 추가하십시오. – darvids0n

답변

6

@ darvids0n에서 알 수 있듯이 당신은 ASIHTTPRequest를 사용할 수 있습니다, 또는 당신은 또한 다음과 같이 표준 아이폰 OS NSMutableURLRequest 방법을 사용 할 수 있습니다 : 당신이 그것을 할 선택 그러나

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:myURL]; // Assumes you have created an NSURL * in "myURL" 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:myJSONData]; // Assumes you have created an NSData * for your JSON 
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"]; 

, 당신은 당신의 Objective-을 변환해야합니다 C 개체를 JSON 문자열로 변환 한 다음이를 NSData로 변환합니다. 여기에 SBJSON 프레임 워크를 사용하여 두 단계를 동시에 수행하는 방법의 예가 있습니다.

SBJsonWriter *writer = [[SBJsonWriter alloc] init]; 
NSData *myJSONData = [writer dataWithObject:myDataDictionary]; 

상기는 JSON 문자열 사전에 변환 한 후 문자열 UTF8 인코딩을 사용을 NSData에 해당 문자열로 변환한다. 다른 인코딩을 원할 경우 [writer stringWithObject:myDataDictionary]을 사용하고 인코딩해야합니다.

+0

그래서 4 개의 객체 (lastmodified, passengerID, ...)로 NSDictionary를 만들고이를 NSData로 변환하고 마지막으로 json 파서를 사용하여 JSON 데이터로 변환해야합니다. – John

+0

일반적으로 개체를 사전에 배치 한 다음 SBJSON (http://stig.github.com/json-framework/)과 같은 프레임 워크를 사용하여 해당 사전을 JSON 문자열로 변환합니다. SBJSONStreamWriter 클래스는 NSDictionary를 바이트 스트림으로 변환 할 수있는 클래스입니다. 델리게이트로 자신을 설정하여 NSData 객체에 추가 할 수 있습니다. NSData가 있으면 HTTP POST 요청에 추가 할 수 있습니다. –

+0

몇 가지 예를 들자면 JSONString으로 setHTTPBody가 나온 것입니다. 흠? – John