使用iOS发送JSON请求 [英] Send JSON request with iOS

查看:96
本文介绍了使用iOS发送JSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用iOS应用发送JSON请求时,我遇到了问题。
我必须发送以下内容:

I'm having an issue when i'm trying to send JSON request with an iOS app. I have to send something like this :

http://url/User/Create/{"newsletter" : 1,"password" : "sdsd", ...}

但请求不是在应用程序上执行此操作时有效:

But the request isn't valid when doing this on the app :

 NSURL   *url = [NSURL URLWithString:@"http://url/User/Create/"];
NSData *jsonData;

NSDictionary *dic = @{
                      @"login" : @"sdsd",
                      @"password" : @"sdsd",
                      @"newsletter" : @1,
                      @"firstname" : @"sdsd",
                      @"lastname" : @"sdsd",
                      @"email" :  @"sdsd@hotmail.fr"};
jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];

如何以有效格式发送请求?

How can i send the request in a valid format ?

推荐答案

HttpRequestSenderDelegate.h

HttpRequestSenderDelegate.h

@protocol HttpRequestSenderDelegate <NSObject>

-(void) didFinishLoading:(BOOL)success data:(NSData*)data;

@end

HttpPostRequestSender.h

HttpPostRequestSender.h

@protocol HttpRequestSenderDelegate;
@interface HttpPostRequestSender : NSObject

- (id)initWithDelegate:(id<HttpRequestSenderDelegate>) delegate;
- (void)send:(NSString*)url postParams:(NSString*)postParams;
- (void)cancelDownload;

@end

HttpPostRequestSender.m

HttpPostRequestSender.m

#import "HttpPostRequestSender.h"
        #import "HttpRequestSenderDelegate.h"

        @interface HttpPostRequestSender ()
        @property (nonatomic, weak) id<HttpRequestSenderDelegate> delegate;
        @property (nonatomic, strong) NSMutableData *activeDownload;
        @property (nonatomic, strong) NSURLConnection *dataConnection;
        @end

        @implementation HttpPostRequestSender
        @synthesize delegate = _delegate,
                    activeDownload = _activeDownload,
                    dataConnection = _dataConnection;

        - (id)initWithDelegate:(id<HttpRequestSenderDelegate>) delegate
        {
            self = [super init];
            if (self) {
                self.delegate = delegate;
            }
            return self;
        }

        - (void)cancelDownload
        {
            [self.dataConnection cancel];
            self.dataConnection = nil;
            self.activeDownload = nil;
        }

        - (void)send:(NSString*)url postParams:(NSString*)postParams
        {
            NSURL *nsurl = [NSURL URLWithString:url];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl
                                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                               timeoutInterval:60.0];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
            NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            self.dataConnection = conn;

        }

        - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
        {
            self.activeDownload = [[NSMutableData alloc] init];
        }

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

        - (void)connectionDidFinishLoading:(NSURLConnection *)connection
        {
            [self.delegate didFinishLoading:YES data:self.activeDownload];
            self.dataConnection = nil;
            self.activeDownload = nil;
        }

        - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
        {
            UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
            [errorView show];
            [self.delegate didFinishLoading:NO data:nil];
            self.dataConnection = nil;
            self.activeDownload = nil;
        }

        @end

:MyViewController .h

in your view controller : MyViewController.h

#import <UIKit/UIKit.h>
#import "HttpRequestSenderDelegate.h"

    @interface MyViewController : UIViewController <HttpRequestSenderDelegate>
    @end

MyViewController.m

MyViewController.m

    #import "MyViewController.h"
        #import "HttpPostRequestSender.h"


        @interface MyViewController ()
        @property (nonatomic, strong) HttpPostRequestSender *requestSender;
        @end

        @implementation MyViewController
        @synthesize requestSender = _requestSender;

    -(HttpPostRequestSender*) requestSender
    {
        if(_requestSender == nil) _requestSender = [[HttpPostRequestSender alloc] initWithDelegate:self];
        return _requestSender;
    }

- (void)viewDidLoad
{
     //for example i send the request in the view did load

     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
     NSString *url = @"your url";
     //post params
     NSString *postParams =@"login=sdsd&password=sdsd&email=sdsd@hotmail.fr";
     [self.requestSender send:url postParams:postParams];
}           

- (void) didFinishLoading:(BOOL)success data:(NSData *)data
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    if(success && data != nil) {
          //here you can parse the response
    }
}

@end

这篇关于使用iOS发送JSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆