2013-04-09 88 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