在HTTPBody中设置NSDictionary并使用POST方法发送

时间:2014-02-26 06:52:11

标签: ios objective-c json nsmutableurlrequest

我想使用POST方法调用Web服务。我需要发布一个带有URL的字典。我的Web服务参数如下:

ConversationMessage {
       authorUserId (string, optional),
       subject (string, optional),
       hasAttachment (boolean, optional),
       conversationId (string, optional),
       attachment (DigitalAsset, optional),
       content (string, optional),
       title (string, optional),
       urgency (boolean, optional),
       searchable (Map[String,Object], optional)
}

DigitalAsset {
        id (string, optional),
        assetUrl (string, optional),
        assetContent (string, optional),
        thumbGenerated (boolean, optional),
        fileName (string, optional)
}  

Map[String,Object] {
        empty (boolean, optional)
}

以下是我的要求:

    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setValue:@"test title" forKey:@"title"];
    [dict setValue:@"test message" forKey:@"content"];
    [dict setValue:@"0" forKey:@"urgency"];

    [arr addObject:[NSMutableDictionary dictionaryWithObject:dict forKey:@"ConversationMessage"]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:strUrl]];
    [request setTimeoutInterval:10.0];
    [request setHTTPMethod:strMethod];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body=[[NSMutableData alloc]init];
    for (NSMutableDictionary *dict in array) {

      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
      [body appendData:jsonData];
}

[request setHTTPBody:body];

但是我收到以下错误:

服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持

5 个答案:

答案 0 :(得分:7)

请找到将数据发布到网络服务的以下代码。请注意,这是我在我的一个申请中使用的样本。

//json format to send the data
jsondata = [NSJSONSerialization dataWithJSONObject:"NSDictionary variable name"
                                               options:NSJSONWritingPrettyPrinted
                                                 error:&error];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [jsondata length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:jsondata];

希望这有帮助。

从您的评论“服务器拒绝此请求”服务器是否支持JSON或XML格式。

答案 1 :(得分:2)

请尝试以下代码:

NSString *params = [self makeParamtersString:dictData withEncoding:NSUTF8StringEncoding];
NSData *body = [params dataUsingEncoding:NSUTF8StringEncoding]; 
[request setHTTPBody:body];
[request setHTTPMethod:@"POST"];

- (NSString*)makeParamtersString:(NSDictionary*)parameters withEncoding:(NSStringEncoding)encoding
{
    if (nil == parameters || [parameters count] == 0)
        return nil;

    NSMutableString* stringOfParamters = [[NSMutableString alloc] init];
    NSEnumerator *keyEnumerator = [parameters keyEnumerator];
    id key = nil;
    while ((key = [keyEnumerator nextObject]))
    {
        NSString *value = [[parameters valueForKey:key] isKindOfClass:[NSString class]] ?
        [parameters valueForKey:key] : [[parameters valueForKey:key] stringValue];
        [stringOfParamters appendFormat:@"%@=%@&",
         [self URLEscaped:key withEncoding:encoding],
         [self URLEscaped:value withEncoding:encoding]];
    }

    // Delete last character of '&'
    NSRange lastCharRange = {[stringOfParamters length] - 1, 1};
    [stringOfParamters deleteCharactersInRange:lastCharRange];
    return stringOfParamters;
}

- (NSString *)URLEscaped:(NSString *)strIn withEncoding:(NSStringEncoding)encoding
{
    CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)strIn, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", CFStringConvertNSStringEncodingToEncoding(encoding));
    NSString *strOut = [NSString stringWithString:(__bridge NSString *)escaped];
    CFRelease(escaped);
    return strOut;
}

答案 2 :(得分:1)

您可以尝试形成以下格式

NSString *parameter = [NSString stringWithFormat:@"title=testtitle&content=testmessage&urgency=0"];

NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

然后将其设置为正文

[theRequest setHTTPBody:parameterData];

答案 3 :(得分:0)

NSMutableURLRequest有一个setHTTPBody:方法,可以将NSData* jsonData作为参数。从表面上看,这似乎是你的问题。你永远不会在上面的代码中调用它。

答案 4 :(得分:0)

我希望您使用流来传递多部分文件。

要传递参数,您应该在传递多部分数据之前使用类似的东西:

NSString *contentDisposition = @"Content-Disposition: form-data; name=\"<name of the parameter with double quotes>\"";

NSString *contentType = @"Content-Type: application/json; charset=UTF-8";

遍历所有参数&amp;附加contentDisposition&amp; contentType由边界字符串分隔。

格式如下:

-----------------------------14737809831466499882746641449
Content-Disposition: form-data; name="title" 
Content-Type: application/json; charset=UTF-8
test title

-----------------------------14737809831466499882746641449
Content-Disposition: form-data; name="content"
Content-Type: application/json; charset=UTF-8
test message

-----------------------------14737809831466499882746641449

Content-Disposition: form-data; name=multipartFile; filename="<fileName>"
Content-Type: text/plain

将此字符串转换为NSData并附加文件和setHttpBody的多部分数据。

希望它有所帮助。