iPhone 애플리케이션에 대한 응답으로 JSON 객체를 얻는 HTTP Post 요청을하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/264140

문제

서버에서 실행되는 웹 서비스가 XML 형식 또는 JSON 형식으로 데이터를 반환합니다. JSON 형식을 요청하고 싶지만 HTTP Post 메소드를 사용하고 싶었습니다.

도움이 크게 감사드립니다.

미리 감사드립니다.

도움이 되었습니까?

해결책

이것은 JSON Post 요청에 대해 작동하는 코드이며, TouchJson 프레임 워크는 JSON을 구문 분석하는 데 사용됩니다.

NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil];
NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];

[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(@"%@", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", theBodyData);
[theRequest setHTTPBody:theBodyData];

NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];
NSLog(@"%@", theResponseDictionary);
NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"];
[self setValue:theGreeting forKey:@"greeting"];

다른 팁

당신의 질문이 정확히 무엇인지 확실하지 않습니다. 그러나 Google "Touchjson"은 시작하는 데 도움이됩니다.

오류와 메모리 누출에 대해 죄송하지만 다음과 같은 것은 어떻습니까?

CFURLRef url = CFURLCreateWithString(NULL, CFSTR("http://example.com/post"), NULL);
CFHTTPMessageRef msg = CFHTTPMessageCreateRequest(
    NULL,
    CFSTR("POST"),
    url,
    kCFHTTPVersion1_1);

const char *body = "key=value&id=30293";
CFDataRef bodyData = CFDataCreate(NULL, body, strlen(body));
CFHTTPMessageSetBody(msg, bodyData);

CFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(NULL, myRequest);
CFReadStreamOpen(myReadStream);
CFHTTPMessageRef myResponse = CFReadStreamCopyProperty(
    myReadStream,
    kCFStreamPropertyHTTPResponseHeader);

//
// Handle myResponse
//

CFReadStreamClose(myReadStream);
CFRelease(myReadStream);
CFRelease(bodyData);
CFRelease(msg);
CFRelease(url);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top