当我尝试使用iOS应用发送JSON请求时,我遇到了问题。 我必须发送这样的东西:
http://url/User/Create/{"newsletter" : 1,"password" : "sdsd", ...}
但是在应用程序上执行此操作时请求无效:
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];
如何以有效格式发送请求?
答案 0 :(得分: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];
}
答案 1 :(得分:1)
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
视图控制器中的: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