iPhone-当'&';包含在HTTP请求正文中

iPhone-当'&';包含在HTTP请求正文中,iphone,xml,http-post,nsurlconnection,Iphone,Xml,Http Post,Nsurlconnection,我遇到了一个非常奇怪的问题,与从我的iPhone应用程序发送POST请求有关 应用程序需要将HTTP post数据发送到第三方服务。请求是XML,它将得到XML响应。以下是我发送请求的代码: -(void)sendRequest:(NSString *)aRequest { //aRequest parameter contains the XML string to send. //this string is already entity-encoded isData

我遇到了一个非常奇怪的问题,与从我的iPhone应用程序发送POST请求有关

应用程序需要将HTTP post数据发送到第三方服务。请求是XML,它将得到XML响应。以下是我发送请求的代码:

-(void)sendRequest:(NSString *)aRequest
{
    //aRequest parameter contains the XML string to send.
    //this string is already entity-encoded
    isDataRequest = NO;
    //the following line will created string REQUEST=<myxml>
    NSString *httpBody =  [NSString stringWithFormat:@"%@=%@",requestString,aRequest];
    //I'm not sure what this next string is doing, frankly, as I didn't write this code initially
    httpBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)httpBody, NULL, CFSTR("+"), kCFStringEncodingUTF8) autorelease];   
    NSData *aData = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kOOURLRequest]] autorelease]; 
    [request setHTTPBody:aData];
    [request setHTTPMethod:@"POST"];
    self.feedURLConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
}
按预期发送,并按预期接收正确的响应

但是,当请求包含
&
字符(特别是在“search”元素中)时,如下所示:

<?xml version="1.0"?>
<request type="search" group="0" language="en" version="2.5.2">
    <auth>
        <serial>623E1579-AC18-571B-9022-3659764542E7</serial>
    </auth>
    <data>
        <location>
            <lattitude>51.528536</lattitude>
            <longtitude>-0.108865</longtitude>
        </location>
        <search>&amp; archive</search>
    </data>
</request>

623E1579-AC18-571B-9022-3659764542E7
51.528536
-0.108865
&;档案文件
只有
&
字符之前的所有内容才会发送到服务器。服务器似乎没有接收到此字符以外的任何内容。请注意,我有一个在Android应用程序中运行的几乎相同的代码,并且一切都正常工作,因此在服务器上这不是一个问题


任何想法,我可以得到这个固定将不胜感激

多亏了扎夫的评论,我终于把它整理好了。我使用WireShark查看实际发送到服务器的内容,发现请求没有完全编码。在最后一个HTTP正文中,出现了实际的符号
&
&;
的一部分)。这在服务器端自然不能很好地工作,因为它接收到如下内容:

REQUEST=first_half_of_request&amp;second_half_of_request
当服务器解码POST变量时,
&
被用作变量的分隔符,因此请求变量仅设置为请求的前半部分-所有内容直到
&
字符

解决办法很简单。一致

httpBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)httpBody, NULL, CFSTR("+"), kCFStringEncodingUTF8) autorelease];

CFSTR(“+”)
替换为
CFSTR(“+&”)
,以对
&
进行编码。现在,这与实体编码(
&;amp;
用于
&
)相结合,导致向服务器发送正确的数据并接收正确的响应。

使用WireShark或Charles之类的网络监视器查看实际发送的内容。在处理数据和发送数据之间的某个时间检查字符串(NSLog it)。在您对它进行的所有处理中,它可能会被截断。
httpBody = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)httpBody, NULL, CFSTR("+"), kCFStringEncodingUTF8) autorelease];