2012-02-24 66 views
0

我有一個非常奇怪的問題,涉及從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>&amp; archive</search> 
    </data> 
</request> 

只有一切都交給了&字符發送到服務器。除了這個角色之外,服務器似乎沒有收到任何東西。請注意,我有一個非常相同的代碼在Android應用程序中工作,並且一切正常,所以它不是服務器上的問題。

任何想法,我可以得到這個固定將不勝感激!

+0

使用像WireShark或Charles這樣的網絡監視器來查看實際發送的內容。 – zaph 2012-02-24 13:30:06

+0

查看字符串(NSLog它)在處理和發送它之間的某個時候。它可能會在你做的所有處理中被截斷。 – 2012-02-24 13:45:49

回答

0

感謝Zaph的評論,我終於整理了它。我使用WireShark來查看實際發送到服務器的內容,並發現請求未完全編碼。在最終的HTTP主體中,實際符號&存在(&amp;的一部分)。這自然也沒有在服務器端很好地工作,因爲它是接收類似:

REQUEST=first_half_of_request&amp;second_half_of_request 

當服務器解碼的POST變量,&被作爲變量的分離,因此請求變量只有設置爲first_half_of_request - 一切都達到&字符。

該解決方案非常簡單。在線路

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

CFSTR("+")替換與CFSTR("+&")編碼&爲好。現在,結合實體編碼(&amp;,&),導致正確的數據被髮送到服務器並且收到正確的響應。