2011-08-13 79 views
2

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

是问题的事实,我在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]; 
+0

你回应什么回应? – lifemoveson

+0

返回的响应是我指定要从GET请求返回的默认文本,即“Hello World!”。 – jdb1a1

+0

我们能否看到WCF部分?特别是与[Attributes] – Oli

回答

1

我结束了使用ASIHTTPRequest运行POST请求到WCF REST服务,现在一切似乎都运行顺利。这意味着可能有某种URL编码机制用于API关键字,后者在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]; 
+0

+1对于尼斯答案.. :)) – mAc

0

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

+0

是的,我试过了,它没有改变结果。不过谢谢你的想法。 – jdb1a1

+0

RE:“问题是我在NSMutableRequest的URL中指定API密钥的事实?服务器如何期待API密钥进入? – Oli

+0

作为URL的一部分,即,http://www.myserver.com/myservice?apikey=12345678-1234-1234-1234-123456789876 – jdb1a1