我有一个非常奇怪的问题,涉及从iPhone应用程序发送POST请求。iPhone - HTTP请求体中包含'&'时的奇怪行为
该应用需要将HTTP发布数据发送给第三方服务。请求是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];
}
这只要完美的作品以及请求XML不包含&
符号,例如,该XML请求:如预期
<?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>archive</search>
</data>
</request>
发送并按预期收到正确的答复。
然而,当请求中包含&
字符(特别是在“搜索”元素) - 像这样:
<?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>& archive</search>
</data>
</request>
只有一切都交给了&
字符发送到服务器。除了这个角色之外,服务器似乎没有收到任何东西。请注意,我有一个非常相同的代码在Android应用程序中工作,并且一切正常,所以它不是服务器上的问题。
任何想法,我可以得到这个固定将不胜感激!
使用像WireShark或Charles这样的网络监视器来查看实际发送的内容。 – zaph 2012-02-24 13:30:06
查看字符串(NSLog它)在处理和发送它之间的某个时候。它可能会在你做的所有处理中被截断。 – 2012-02-24 13:45:49