1. 程式人生 > >老賴 封裝的一個 資料 請求函式 HTTPENGINE

老賴 封裝的一個 資料 請求函式 HTTPENGINE

+ (NSData *)synchronizeDataWithURL:(NSString *)urlString withBody:(NSString *)body

{

    NSURLResponse *response = nil;

    NSError *error = nil;

// 解決URL帶中文發生NSURLErrorDomain Code=-1000 "錯誤的 URL"

    NSString *encodeUrlString = [urlString

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//

    NSURL *url = [NSURL URLWithString:encodeUrlString];

NSMutableURLRequest *request = [NSMutableURLRequest

                                    requestWithURL:url

cachePolicy:NSURLRequestUseProtocolCachePolicy

                                    timeoutInterval:30.0];

    if (body) {

NSData *bodyData = [body

dataUsingEncoding:NSUTF8StringEncoding

                              allowLossyConversion:YES];

        NSString *dataLength = [NSString stringWithFormat:@"%d", [bodyData length]];

        [request setHTTPBody:bodyData];

        [request setValue:dataLength forHTTPHeaderField:@"Content-Length"];

        [request

setValue:@"text/xml; charset=utf-8"forHTTPHeaderField:@"Content-Type"];

    }

    [UIApplicationsharedApplication].networkActivityIndicatorVisible = YES;

    NSData *data = [NSURLConnection sendSynchronousRequest:request

                                         returningResponse:&response

                                                     error:&error];

    [UIApplicationsharedApplication].networkActivityIndicatorVisible = NO;

    NSLog(@"error:%@\nresponse:%@", error, response);

NSLog(@"reponse string now:%@",

          [[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);

    return data;

}