我有一個非常奇怪的問題,涉及從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