2013-03-21 56 views
0

我试图发送一些web请求到后端API我已经在我的web服务器上安装。 但是,为了使事物具有通用性,我希望将完整的JSON对象发送到后端,并在那里对所有数据进行过滤以确定请求的内容,要传递哪些参数等。iOS - 如何将JSON对象附加到Web请求? (不使用NSURLConnection)

I将从一个类发出很多请求到不同的服务,所以我不想使用NSURLConnection,因为它无法过滤完成处理程序中的所有结果,以确定哪个请求最初被提取。

我喜欢NSURLConnection的是如何让你附加这样一个JSON对象,但我想知道如何用不同的方法去做(比如[NSData的dataWithContentsOfURL:])

NSMutableDictionary *postObject = [[NSMutableDictionary alloc] init]; 
[postObject setValue:@"login" forKey:@"request"]; 
[postObject setValue:inputUsername.text forKey:@"userName"]; 
[postObject setValue:inputPassword.text forKey:@"password"]; 

NSData *postData = [NSJSONSerialization dataWithJSONObject:postObject options:0 error:NULL]; 
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:@"WEB_URL"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:postData]; 
[request setTimeoutInterval:20]; 

有什么建议?

+0

不是答案,但..为什么你不使用RestKit? - https://github.com/RestKit/RestKit它使得服务工作更容易。 – 2013-03-21 21:46:08

回答

1

我这样做的方式是制作一个带有NSURLConnection的NSObject类,并在该类上设置Property Tag。然后你有NSObject/NSURLConnection类的连接返回自己的委托下载完成时。你有一个类似于下面的 - (void)downloadFinished例子的方法来处理委托中的回复。

在NSObject类中,您使用NSJsonSerialization将NSDictionary转换为Json并将其附加到NSURLConnection。

我希望我可以把它连你的JsonHelper类Github上,但是我还没有上传至Github上尚未:(

示例请求:

NSDictionary *post = [NSDictionary dictionaryWithObjectsAndKeys:@"Json_Value",@"Json_Key",nil]; 

JsonHelper *jsonHelper = [[JsonHelper alloc]initWithURL:@"http://mycoolwebservice.com" withDictionary:post 
withMethod:@"POST" showIndicator:NO withDelegate:self withCache:NO]; 
[jsonHelper setTag:1]; 
[jsonHelper connectionStart]; 

代表回复例:

-(void)downloadFinished:(id)sender 
{ 
    if ([sender isKindOfClass:[JsonHelper class]]) { 

    NSError *error = nil; 
    JsonHelper *jsonHelper = (JsonHelper*)sender; 
     NSData *data = [[NSData alloc]initWithData:jsonHelper.receivedData]; 
     NSString *returnString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];  

    if (jsonHelper.tag == 0) { 

    // Do Something 
    } 

    else if (jsonHelper.tag == 1) { 

    // Do Something Else 
    } 
    }  
} 

使用此示例编写自己的自定义类来做更多或更少的事情应该不会太困难

+0

是的,它击败了我试图做的目的。我可以使用NSURLConnection,它是完成处理的委托。我想把整个过程放在它自己的方法中,试着让事情有组织并易于遵循。 – JimmyJammed 2013-03-21 23:33:22

+1

如果你想保留它,块看起来是合乎逻辑的选择。这可能会帮助你:http://blog.logichigh.com/2010/09/12/cocoa-blocks/ – 2013-03-21 23:44:50

+0

和另一个:http://messagesenttodeallocatedinstance.wordpress.com/2012/04/10/nsurlconnection-with- blocks/ – 2013-03-21 23:46:46

相关问题