2013-08-27 22 views
0

我正在創建一個iPhone應用程序,我需要將數據發送到服務器。使用NSURLConnection,我可以發送數據,但我的數據發送兩次。我只得到一次迴應。 任何人都可以說明爲什麼會出現這種情況NSURLConnection在服務器上發送兩次數據

這裏是我的代碼

NSURL *url=[NSURL URLWithString:[APIServiceURL geturl]]; 
     NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url]; 
     NSString *msgLength=[NSString stringWithFormat:@"%d",[soapMsg1 length]]; 
     [req addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; 
     [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 
     [req addValue:@"http://tempuri.org/InsertPostComment" forHTTPHeaderField:@"SOAPAction"]; 
     [req setHTTPMethod:@"POST"]; 
     [req setHTTPBody:[soapMsg1 dataUsingEncoding:NSUTF8StringEncoding]]; 

     // Response 
     NSHTTPURLResponse *urlResponse=nil; 
     NSError *error; 
     connection =nil; 
     connection=[[NSURLConnection alloc]initWithRequest:req delegate:self]; 
     NSData *responseData; 
     ; 

     if (connection) 
     { 
      responseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&urlResponse error:&error]; 
     } 
     else 
     { 
      NSLog(@"not connected to server"); 
     } 

     if ([responseData length]>0) 
     { 

      NSString *responseString=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; 
      NSLog(@"responseString %@",responseString); 
      responseString =nil;} 

感謝

+0

我們怎麼知道不知道代碼? – Raptor

+0

根據您發佈的代碼,只有一個請求已經完成,所以您得到了一次響應。你想要問什麼?闡述。 –

+0

是隻做出一個請求,但數據在服務器上發佈兩次。 – user2185354

回答

2

與您的代碼2個請求製成。

創建NSURLConnection時會發送第一個。 [[NSURLConnection alloc] initWitRequest: delegate:]創建連接並異步啓動請求,將數據發回給您指定的委託。

,當你調用

[NSURLConnection sendSynchronousRequest:req returningResponse:&urlResponse error:&error]; 

如果你想要做一個同步調用到您的端點,第二個是由:

NSData *responseData; 
responseData=[NSURLConnection sendSynchronousRequest:req returningResponse:&urlResponse error:&error]; 

if (!error) 
{ 
    // Do your stuff with the response data 
} 
else 
{ 
    NSLog(@"not connected to server with error %@", error.debugDescription); 
} 

很好看的的URLConnection:Apple Reference

0

使用NSUrlConnection委託來獲取這兩個響應。當且僅當您的服務器針對您發佈的日期發送2個響應時,U才能得到2個響應。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSString *response = [[NSString alloc] initWithBytes:[data bytes] length:[data length] 
                encoding:NSUTF8StringEncoding]; 
} 

它應該工作。