2012-08-06 53 views
0

我知道有很多關於這個問題,但沒有人似乎爲我想做的事情工作。我想改變一個變量的值讓我們說,我有這個文件:iPhone - Http Post:發送一個值到網絡xml

</Courbe> 
<tempset>140</tempset> 
</Courbe> 

我希望我的HTTP POST請求更改此值。我該怎麼做呢?

我已經嘗試過這樣的事情:

- (IBAction)changeTemp:(id)sender 
{ 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL  URLWithString:@"http://207.134.145.16:50001/Courbe.xml"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"]; 

NSString *xmlString = @"<tempset>137</tempset>"; 

[[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

是不是這樣呢?謝謝你的幫助!

+0

你有沒有調用'-start'或'+ sendSynchronousRequest:returningResponse:error:'? (見[NSURLConnection](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html)) – 2012-08-06 18:31:53

+0

不,因爲這是在一個按鈕,也許我應該編輯它。但我不應該說這是對的? – 2012-08-06 18:32:47

+0

上面的代碼只創建一個連接對象,但不會開始請求/響應事務。 – 2012-08-06 18:34:31

回答

2

網址編碼的xmlString,則:

NSData *postData = [xmlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
[request setHTTPBody:postData]; 
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; 

要發送,使用這樣的:

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {}]; 

此前的iOS5,您可以異步發送這種方式:

// make the request and an NSURLConnection with a delegate 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 

// create a property to hold the response data, then implement the delegate methods 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    responseData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    [responseData release]; 
    [textView setString:@"Unable to fetch data"]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSString *responseString = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease]; 
} 
+0

錯過了你有xml數據。剛剛編輯。 – danh 2012-08-06 18:39:59

+0

這可能是好的,但我忘了提及,我正在開發4.0我的不好的+1嘗試,雖然!謝謝 – 2012-08-06 19:42:02

+0

@ BenLefebvre,你的問題的原始觀點似乎是如何設置帖子的主體。這在我的答案的前幾行代碼中得到了證明。如何發送請求是一個不同的問題。我將編輯我的答案以包含iOS <5。 – danh 2012-08-07 02:54:25