Send JSON request with iOS

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

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 ?

回答1:

-(void)tryThis   {   NSString *a=@"{'login' : 'sdsd', 'password' : 'sdsd', 'newsletter' : 1, 'firstname' : 'sdsd', 'lastname' : 'sdsd',  'email' :  'sdsd@hotmail.fr'}";     a= [a stringByReplacingOccurrencesOfString:@"'" withString:@"\"" options:NSCaseInsensitiveSearch range:NSMakeRange (0, [a length])];   NSData* postData= [a dataUsingEncoding:NSUTF8StringEncoding];   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https:***********your url"]];   [request setHTTPMethod:@"POST"];   [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];    [request setHTTPBody:postData];   NSURLResponse *response = NULL;    NSError *requestError = NULL;    NSData *responseData1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];    NSString *responseString = [[NSString alloc] initWithData:responseData1 encoding:NSUTF8StringEncoding];     }   


回答2:

HttpRequestSenderDelegate.h

@protocol HttpRequestSenderDelegate <NSObject>  -(void) didFinishLoading:(BOOL)success data:(NSData*)data;  @end 

HttpPostRequestSender.h

@protocol HttpRequestSenderDelegate; @interface HttpPostRequestSender : NSObject  - (id)initWithDelegate:(id<HttpRequestSenderDelegate>) delegate; - (void)send:(NSString*)url postParams:(NSString*)postParams; - (void)cancelDownload;  @end 

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 

in your view controller : MyViewController.h

#import <UIKit/UIKit.h> #import "HttpRequestSenderDelegate.h"      @interface MyViewController : UIViewController <HttpRequestSenderDelegate>     @end 

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!