将HTTP Post参数从NSDictionary发送到Web服务

时间:2014-08-30 09:12:35

标签: ios http

我有一个R.E.S.T网络服务等待接收GET和POST Http请求。

我已经构建了一个用于创建,发送和移动这些请求的委托实例的类。

由于某些原因,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;
}

顺便说一下,当发送空数据时,它有效,这意味着它确实发送了请求。

1 个答案:

答案 0 :(得分: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:的多个实现。

我希望它会有所帮助。