Skip to content
DarkKaiser의 블로그
DarkKaiser의 블로그
  • 개발 관련 자료(노션)
  • Raspberry Pi(노션)
  • WD My Cloud(노션)
  • GitHub
DarkKaiser의 블로그

HTTP Request/Response Wrapper 클래스 만들기

DarkKaiser, 2010년 12월 27일2023년 9월 6일

참고 : http://theeye.pe.kr/entry/http-wrapping-class-with-iphone-network-programming

HTTPRequestAppDelegate.m

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // 접속할 주소 설정
    NSString *url = @"http://your.webpage.url";
    
    // HTTP Request 인스턴스 생성
    HTTPRequest *httpRequest = [[HTTPRequest alloc] init];
    
    // POST로 전송할 데이터 설정
    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:@"eye",@"name",@"http://theeye.pe.kr", @"home", nil];
    
    // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
    
    // 페이지 호출
    [httpRequest requestUrl:url bodyObject:bodyObject];
    
    [window makeKeyAndVisible];
}

HTTPRequest.h

#import <Foundation/Foundation.h>
 
@interface HTTPRequest : NSObject
{
    NSMutableData *receivedData;
    NSURLResponse *response;
    NSString *result;
    id target;
    SEL selector;
}
 
- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)setDelegate:(id)aTarget selector:(SEL)aSelector;
 
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLResponse *response;
@property (nonatomic, assign) NSString *result;
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL selector;
 
@end

HTTPRequest.m

#import "HTTPRequest.h"

@implementation HTTPRequest

@synthesize receivedData;
@synthesize response;
@synthesize result;
@synthesize target;
@synthesize selector;

- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject
{
    // URL Request 객체 생성
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:5.0f];
    
    // 통신방식 정의 (POST, GET)
    [request setHTTPMethod:@"POST"];
    
    // bodyObject의 객체가 존재할 경우 QueryString형태로 변환
    if(bodyObject)
    {
        // 임시 변수 선언
        NSMutableArray *parts = [NSMutableArray array];
        NSString *part;
        id key;
        id value;
        
        // 값을 하나하나 변환
        for(key in bodyObject)
        {
            value = [bodyObject objectForKey:key];
            part = [NSString stringWithFormat:@"%@=%@", [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                                        [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            [parts addObject:part];
        }
        
        // 값들을 &로 연결하여 Body에 사용
        [request setHTTPBody:[[parts componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    // Request를 사용하여 실제 연결을 시도하는 NSURLConnection 인스턴스 생성
    NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
    
    // 정상적으로 연결이 되었다면
    if(connection)
    {
        // 데이터를 전송받을 멤버 변수 초기화
        receivedData = [[NSMutableData alloc] init];
        return YES;
    }
    
    return NO;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse
{
    // 데이터를 전송받기 전에 호출되는 메서드, 우선 Response의 헤더만을 먼저 받아 온다.
    //[receivedData setLength:0];
    self.response = aResponse;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 데이터를 전송받는 도중에 호출되는 메서드, 여러번에 나누어 호출될 수 있으므로 appendData를 사용한다.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // 에러가 발생되었을 경우 호출되는 메서드
    NSLog(@"Error: %@", [error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 데이터 전송이 끝났을 때 호출되는 메서드, 전송받은 데이터를 NSString형태로 변환한다.
    result = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    
    // 델리게이트가 설정되어있다면 실행한다.
    if(target)
    {
        [target performSelector:selector withObject:result];
    }
}

- (void)setDelegate:(id)aTarget selector:(SEL)aSelector
{
    // 데이터 수신이 완료된 이후에 호출될 메서드의 정보를 담고 있는 셀렉터 설정
    self.target = aTarget;
    self.selector = aSelector;
}

- (void)dealloc
{
    [receivedData release];
    [response release];
    [result release];
    [super dealloc];
}

@end

위의 예제를 잠깐 다시 살펴보면 requestUrl:bodyObject: 가 호출될 때 bodyObject를 자동으로 queryString으로 변환하여 Request를 보내게 됩니다.

이후에 setDelegate:selector:를 통해 설정한 셀렉터 정보를 가지고 데이터 수신이 끝나 connectionDidFinishLoading: 가 호출되는 시점에 해당 메서드를 호출하게 됩니다. 테스트는 인터넷이 되는 환경에서 해야하고 다음과 같이 잘 되는것을 알 수 있습니다.

Objective-C

글 내비게이션

Previous post
Next post

답글 남기기 응답 취소

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

최신 글

  • AssertJ 소개testCompile ‘org.assertj:assertj-core:3.6.2’ 2017년 9월 14일
  • 자주 사용되는 Lombok 어노테이션 2017년 9월 14일
  • 유니코드 #3 2017년 9월 14일
  • 유니코드 #2 2017년 9월 14일
  • 유니코드 #1 2017년 9월 14일

최신 댓글

    카테고리

    • 개인 자료 (1)
      • 일기 (1)
    • 주절주절 (7)
    • 프로그래밍 갤러리 (16)
    • 프로그래밍 언어 (186)
      • Java (29)
      • C/C++/VC++ (114)
      • C# (11)
      • Visual Basic (6)
      • 안드로이드 (9)
      • Objective-C (5)
      • JavaScript (4)
      • JSP/Servlet (2)
      • Python (4)
      • 어셈블러 (1)
    • 개발++ (44)
      • Book (11)
        • Joel On Software (10)
      • 프로젝트 관리 (6)
      • Maven (1)
      • 디버깅 (1)
      • DirectX (1)
      • Silverlight (1)
      • RESTful (1)
      • Hacking (1)
      • WDM (4)
      • VoIP (5)
      • 기타 (1)
    • 개발 도구 (15)
      • eclipse (14)
      • Sublime Text (1)
    • 네트워크 (7)
    • 설치 및 배포 (7)
      • InstallShield (2)
      • NSIS (4)
    • 버전 관리 (9)
      • Git (2)
      • CVS (2)
      • Subversion (5)
    • 데이터베이스 (7)
      • Oracle (3)
      • Sybase (2)
      • MS-SQL (2)
    • 단위테스트 (3)
      • JUnit (1)
      • NUnit (2)
    • 버그추적시스템 (2)
      • mantis (2)
    • 운영체제 (7)
      • Windows (5)
      • 리눅스 (2)
    • WAS (3)
      • WebLogic (3)
    • 디자인패턴 (1)
    • 디지털 이미지 프로세싱 (16)

    태그

    Abstract ActiveX AfxParseURL Automation boost devenv.exe event EventLogTraceListener Hover interface IO iTextSharp JAD jar JavaScript Joel Leave MFC Monitor msdev.com MSDN mutable PDF Properties RAW Saturation SHGetFolderPath SHGetKnownFolderPath SQLite STLTask String TextWriterTraceListener URL VI 권한 데이터소스 디컴파일러 문자열 스레드 동기화 스레드 생성 실용주의 프로그래머 자동화 테스팅 파일포맷 프리컴파일

    메타

    • 로그인
    • 엔트리 피드
    • 댓글 피드
    • WordPress.org
    ©2025 DarkKaiser의 블로그 | WordPress Theme by SuperbThemes