0

我正在我的 iPhone 应用程序中访问 xml Web 服务。但我无法从服务器获取适当的数据。我在 NSURLConnection 的 connectionDidFinishLoading 委托方法中遇到以下错误。

soap:ServerServer 无法处理请求。---> 对象引用未设置为对象的实例。

以下是我的代码:

NSString *deviceID = [OpenUDID value];

NSString *soapMsg = [NSString stringWithFormat:
                     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                     "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                     "<soap:Header>"
                     "<AuthHeader xmlns=\"http://tempuri.org/\">"
                     "<Username>admin</Username>"
                     "<Password>admin</Password>"
                     "</AuthHeader>"
                     "</soap:Header>"
                     "<soap:Body>"
                     "<WsGetAllDrugDetailsXML xmlns=\"http://tempuri.org/\">"
                     "<UserId>%d</UserId>"
                     "<IMEI>%@</IMEI>"
                     "</WsGetAllDrugDetailsXML>"
                     "</soap:Body>"
                     "</soap:Envelope>",[Appdelegate.UserID intValue],deviceID];


//---print it to the Debugger Console for verification---
NSLog(@"%@", soapMsg);

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:Appdelegate.wsURL];

//---set the various headers---
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];

[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"http://tempuri.org/WsGetAllDrugDetailsXML" forHTTPHeaderField:@"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"];

//---set the HTTP method and body---
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {

    webData = [[NSMutableData data] retain];
}

我无法预测我这边出了什么问题。或者是服务器端的错误,我没有收到数据。请帮助我。在此先感谢!

4

1 回答 1

0

您的Content-Length值不正确:

长度必须以字节为单位。NSString 的length方法返回 UTF-16 代码单元的数量。

您可以按如下方式修复它:

NSData* bodyData = [soapMsg dataUsingEncoding:NSUTF8StringEncoding];
[req addValue:[NSString stringWithFormat:@"%d",(int)[bodyData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPBody:bodyData];
于 2014-01-03T12:04:09.117 回答