为什么我的NSMutableURLRequest失败了?

时间:2014-10-31 12:47:04

标签: ios objective-c nsurlconnection nsmutableurlrequest

我正在尝试从服务器获取数据,但是当我在服务器测试客户端中运行相同的链接时,我从服务器收到{"Message":"Wrong Process.","Success":false,"Cookie":null}的错误消息,我得到了正确的结果。那么请问我的代码中的问题在哪里?

密钥为data

值为<r_PM act=\"par\"/>

- (void)viewDidLoad {

    [super viewDidLoad];

    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/service/par.ashx"]];

    NSString *message = [[NSString alloc] initWithFormat:@"data=<r_PM act=\"par\"/>"];

    NSString *msgLength = [NSString stringWithFormat:@"%lu",(unsigned long)[message length]];

    [postRequest addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [postRequest addValue:msgLength                         forHTTPHeaderField:@"Content-Length"];

    [postRequest setHTTPMethod:@"POST"];
    [postRequest setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection * connection = [[NSURLConnection alloc]
                                    initWithRequest:postRequest
                                    delegate:self startImmediately:NO];

    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                          forMode:NSDefaultRunLoopMode];
    [connection start];

    NSURLResponse *response;
    NSError *err;

    responseData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&err];

    NSLog(@"responseData is: %@", responseData);

    NSString* newStr = [[NSString alloc] initWithData:responseData encoding: ];

    NSLog(@"Results : %@", newStr);

}

1 个答案:

答案 0 :(得分:3)

您正在创建一个请求,其内容类型为XML,但其请求正文不是。 &#34;数据= ...&#34;格式不是XML。如果没有API文档或生成有效请求的示例代码,我们将很难帮助您。

顺便说一句,您的Objective-C代码发出请求两次,一次使用基于委托的NSURLConnection(您尚未共享您的委托实现),然后又使用{{1 }}。只发出一次。如果你喜欢sendSynchronousRequest方法的简单性,我建议你使用它的sendSynchronousRequest兄弟,这也很方便,但不是同步的。


离线,通过检查您从其他工具发送的请求,我们确认问题是

  • 请求为sendAsynchronousRequest而不是application/x-www-form-urlencoded

    因此,将application/xml行替换为:

    Content-Type
  • 数据必须进行百分比转义,例如:

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    

    其中,转义例程的百分比可能类似于:

    NSString *value = @"<r_PM act=\"par\"/>"; 
    NSString *message = [NSString stringWithFormat:@"data=%@", [self percentEscapeString:value]];