2013-04-09 19 views
1

我正在爲我的iOS應用程序使用Web服務。 我知道如何通過URL(不是http Body)發送http post請求並使用NSURLConnection Delegate獲取響應。 但現在有更好的方法,我正在跟蹤Web服務並在請求體中傳遞參數。我在谷歌搜索圖書館,發現thisHttpRequest iOS中的Body參數

但是,代碼對我來說有點困難,我想應該有相同的功能,這可以使這一點更容易。 有沒有?到目前爲止的代碼如下。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
    initWithURL:[NSURL 
    URLWithString:**WebService URL**]]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:@"text/json" forHTTPHeaderField:@"Content-type"]; 

NSString *jsonString = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name]; 

[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; 

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

此代碼中的jsonString是http正文。我想在請求體中傳遞參數。 現在,執行此代碼後,我在NSData變量中得到空值。而我的web服務函數返回一個值,如果執行成功,它也會返回。 我的代碼有什麼問題。 謝謝。

回答

5

謝謝您的回答。最後,我找到了完全正確的解決方案。 我已經使用NSURLConnection委託,我在json中傳遞HTTPBody中的參數。我也接受json的迴應。 但是在httprequestbody中不允許直接發送參數作爲json,所以我們需要將它放在NSData中並設置content-type。

注意:指定內容類型非常重要。

-(void)sendDataToServer:(NSString*)userName :(NSString*)name{ 
{ 
NSArray *keys = [NSArray arrayWithObjects: @"name",@"accountType",@"isOnline",@"username", nil]; 
NSArray *objects = [NSArray arrayWithObjects:name,[NSNumber numberWithBool:false],[NSNumber numberWithBool:false],userName, nil]; 
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

NSString *myJSONString =[jsonDictionary JSONRepresentation]; 
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding]; 
NSLog(@"myJSONString :%@", myJSONString); 
NSLog(@"myJSONData :%@", myJSONData); 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:Your URL string]]; 
[request setHTTPBody:myJSONData]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 


    if (theConnection) { 
     NSLog(@"connected"); 
     receivedData=[[NSMutableData alloc]init]; 
    } else { 

     NSLog(@"not connected"); 
    } 

    } 

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [receivedData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
[receivedData appendData:data]; 
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
NSLog(@"response: %@",responseString); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
// do something with the data 
// receivedData is declared as a method instance elsewhere 
NSLog(@"Succeeded! Received %lu data",(unsigned long)[receivedData length]); 
NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 
NSLog(@"response: %@",responseString); 


NSError *myError = nil; 
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError]; 

// show all values 

for(id key in res) { 

    id value = [res objectForKey:key]; 

    NSString *keyAsString = (NSString *)key; 
    NSString *valueAsString = (NSString *)value; 

    NSLog(@"key: %@", keyAsString); 
    NSLog(@"value: %@", valueAsString); 
} 
} 

P.S:您需要添加用於序列化的json文件(json.h)。

+0

@xmd是iOS中基礎庫的JSON.h部分? – Supertecnoboff 2014-04-15 20:49:17

+0

不,您可以從這裏驗證[link](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/ObjC_classic/_index.html#//apple_ref/doc/uid/20001091) 。 – xrnd 2014-04-22 11:58:29

1

。在你的示例代碼一個錯字,這可以解釋的空結果:

NSString ***jsonString** = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name]; 

[request setHTTPBody:[**xmlString** dataUsingEncoding:NSUTF8StringEncoding]]; 
+0

我剛糾正了我發佈問題的錯誤。但在我的代碼中不一樣。否則會給錯誤。反正現在主要的問題是,如何在請求體中傳遞參數。你有什麼線索vdaubry? – xrnd 2013-04-09 10:11:48

0

退房這個問題nsurlrequest post bodyhttp post encode type

一般來說,機構應符合「鍵=值「格式化

你的問題,你需要一個 」爲您jsonString

[request setHTTPBody:[NSString stringWithFormat:@"postedJson=%@", jsonString]]; 
鍵「

postedJson是通過它在服務器端獲得它的價值的關鍵。 如:

request["postedJson"] 

返回值將是jsonString你construted

+0

我試過提到的方法。 「key = value」,但返回'string'不包含'username'的定義。現在我確定我的代碼或http Body的格式存在一些錯誤。這是我的代碼現在,'NSString * bodyContents = [NSString stringWithFormat:@「username =%@&password =%@&accessToken =%@&name =%@&version =%@&accountType =%@&isOnline =%@」,userName,pass ,令牌名,@ 「假」,@ 「假」,@ 「假」]; ' – xrnd 2013-04-09 19:24:12

+0

@xmd,你不明白我的意思。請檢查最新的答案。 – fengd 2013-04-10 05:47:20

+0

謝謝@ Jun1st。我發佈了適用於我的解決方案。希望它有幫助 – xrnd 2013-04-10 08:29:16