2

我的目标 c 代码有问题。我有一个我构建的受 API 密钥保护的 WCF API,它接受 POST 请求并将它们写入使用 C# 的 Java servlet。无论如何,这在使用 Fiddler 进行测试时效果很好,而不是从目标 C 中很好。当我尝试从我的目标 C 运行 POST 时,它“行为”就像 NSURLMutableRequest 正在寻找一个 GET,因为响应只返回一些默认值我为 GET 方法编写的代码。有谁知道这是为什么,而且,我能做些什么来解决它?这是我使用(非常成功)在目标 C 中发出其他 POST 请求的代码。

问题是我在 NSMutableRequest 的 URL 中指定了 API 密钥吗?这是我唯一能想到的。

这是代码:

NSString* theMessage = [NSString stringWithFormat:@"<MyRequestObject xmlns='http://schemas.datacontract.org/2004/07/MyService'></MyRequestObject>"];

        NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:POST_API_URL] 
            cachePolicy:NSURLRequestUseProtocolCachePolicy
            timeoutInterval:240.0];

        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
        [theRequest setHTTPBody:[theMessage dataUsingEncoding:NSUTF8StringEncoding]];

        NSString *msgLength = [NSString stringWithFormat:@"%d", [theMessage length]];
        [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];

        NSURLResponse* response;
        NSError *error;

        NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
4

2 回答 2

1

我最终使用ASIHTTPRequest向 WCF REST 服务运行 POST 请求,现在一切似乎都运行顺利。这意味着可能存在某种用于 API 密钥的 URL 编码机制,该机制在幕后进行,但没有NSMutableURLRequest人知道。好消息是,我已经解决了这个问题。这是我使用的代码:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:POST_API_URL]];
        [request appendPostData:[[NSString stringWithFormat:@"<MyRequest xmlns='http://schemas.datacontract.org/2004/07/MyService'>all of my request params in here</MyRequest>"] dataUsingEncoding:NSUTF8StringEncoding]];

        [request setRequestMethod:@"POST"];
        [request addRequestHeader:@"Content-Type" value:@"text/xml"];

        [request startSynchronous];
于 2011-08-14T15:52:54.473 回答
0

您是否尝试设置 Content-Length 标头?如果没有将其长度定义为标头,WCF/IIS 可能会忽略正文。

于 2011-08-13T04:31:05.030 回答