2014-08-30 2 views
0

У меня есть веб-служба R.E.S.T, ожидающая получения запроса GET и POST Http.Отправлять параметры HTTP-сообщения из NSDictionary в веб-службу

Я построил класс для создания, отправки и перемещения экземпляров делегирования этих запросов.

По какой-то причине мои параметры в методе POST не отправляются правильно, а результат - тайм-аут запроса (сервер вообще не отвечает).

Я думаю, что это может быть что-то с форматом я создать тело запроса его:

- (NSURLConnection*)requestUrl:(NSString *)url usingMethod:(NSString *)method containingData:(NSDictionary *)data { 
    NSString* dataString = [self createStringFromData:data]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]]; 
    if ([method isEqualToString:HTTP_REQUEST_GET]) 
     request = [self createGetRequest:request withData:dataString]; 
    else if ([method isEqualToString:HTTP_REQUEST_POST]) 
     request = [self createPostRequest:request withData:dataString]; 
    else 
    { 
     NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary]; 
     [errorDetail setValue:@"Http Request Method is Invalid" forKey:NSLocalizedDescriptionKey]; 
     NSError *error = [NSError errorWithDomain:@"com.picomedia.Pico" code:100 userInfo:errorDetail]; 
     [_httpRequestDelegate httpRequestReturnedError:error]; 
     return nil; 
    } 
    //set request time out 
    //show the url and datastring if in debug mode 
    #ifdef DEBUG 
     NSLog(@"Url: %@",[request.URL absoluteString]); 
     NSLog(@"Method: %@", method); 
     NSLog(@"DataString: %@", dataString); 
    #else 
     request.timeoutInterval = 15; 
    #endif 
    // Create url connection and fire request 
    return [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

/** 
Create string from a data dictionary. 
@param data the dictionary to take the data from 
@return the string containing the data 
*/ 
-(NSString*) createStringFromData:(NSDictionary*) data { 
    NSString* dataString = @""; 
    for(NSString* key in data) 
    { 
     NSString* value = (NSString*)[data objectForKey:key]; 
     NSString* keyValuePair = [[[key stringByAppendingString:@"="] stringByAppendingString:[self urlEncodeString:value]] stringByAppendingString:@"&"]; 
     dataString = [dataString stringByAppendingString:keyValuePair]; 
    } 
    if ([dataString length] > 0) 
     dataString = [dataString substringToIndex:[dataString length] - 1]; 
    return dataString; 
} 

/** 
Create an HTTP GET request with data 
@param request the NSMutableURLRequest request 
@param data the string containging key->value pairs of the data. the data should me utf8 and urlencoded 
@return NSMutableURLRequest with the request data 
*/ 
- (NSMutableURLRequest*) createGetRequest:(NSMutableURLRequest*)request withData:(NSString*)data { 
    request.HTTPMethod = HTTP_REQUEST_GET; 
    if (data != nil) 
    { 
     NSString* url = [[[request.URL absoluteString] stringByAppendingString:@"?"]stringByAppendingString:data]; 
     request.URL = [NSURL URLWithString:url]; 
    } 
    return request; 
} 

/** 
Send an Http POST request with a string containg the post data 
@param data the data of the request in string format 
*/ 
- (NSMutableURLRequest*) createPostRequest:(NSMutableURLRequest*)request withData:(NSString*) data { 
    request.HTTPMethod = HTTP_REQUEST_POST; 
    NSString *postLength = [NSString stringWithFormat:@"%d",[data length]]; 

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    // Convert your data and set your request's HTTPBody property 
    NSData *requestBodyData = [data dataUsingEncoding:NSUTF8StringEncoding]; 
    request.HTTPBody = requestBodyData; 
    // Create url connection and fire request 
    return request; 
} 

Кстати, при отправке пустых данных, которые он работает, то есть он отправить запрос.

ответ

0

Если вы действительно хотите сами создать запрос, вам следует вдохновиться частью AFNetworking, которая выполняет эту работу. Библиотека делает именно то, что вы хотите сделать here:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method 
           URLString:(NSString *)URLString 
           parameters:(id)parameters 
            error:(NSError *__autoreleasing *)error 
{ 
    NSParameterAssert(method); 
    NSParameterAssert(URLString); 

    NSURL *url = [NSURL URLWithString:URLString]; 

    NSParameterAssert(url); 

    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; 
    mutableRequest.HTTPMethod = method; 
    mutableRequest.allowsCellularAccess = self.allowsCellularAccess; 
    mutableRequest.cachePolicy = self.cachePolicy; 
    mutableRequest.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies; 
    mutableRequest.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining; 
    mutableRequest.networkServiceType = self.networkServiceType; 
    mutableRequest.timeoutInterval = self.timeoutInterval; 

    mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; 

    return mutableRequest; 
} 

чем есть несколько реализаций requestBySerializingRequest:withParameters:error: в зависимости от кодировки вы хотите использовать для вашего запроса.

Надеюсь, это поможет.

+0

Это действительно отличная каркас, и это упрощает все. Благодаря! –

Смежные вопросы