繁体   English   中英

IOS如何POST删除PUT Rest Api

[英]IOS how to POST GET DELETE PUT Rest Api

我正在构建我的应用程序连接到Rest API,直到现在我只使用以下代码发出了一个GET请求:

//Start login process
NSString *emailstring = email.text;
NSString *passstring = pass.text;

// Create the URL from a string.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myserver.com/Rest/API/users?format=json&email=%@&password=%@",emailstring,passstring]];
NSLog(@"%@",url);

// Create a request object using the URL.
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// Prepare for the response back from the server    
NSHTTPURLResponse *response = nil;
NSError *error = nil;

// Send a synchronous request to the server (i.e. sit and wait for the response)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Reponse from web:%@", response);

// Check if an error occurred    
if (error != nil) {
    NSLog(@"%@", [error localizedDescription]);
    // Do something to handle/advise user.

    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Login error"
                                                      message:@""
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];

}

else {

    // Convert the response data to a string.
    NSString *responseString = [[NSString alloc] initWithData:responseData  encoding:NSUTF8StringEncoding];

    // View the data returned - should be ready for parsing.
    NSLog(@"%@", responseString);

    // Add data to a Plist file for next time
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"login.plist"];

    NSArray *values = [[NSArray alloc] initWithObjects:emailstring,passstring,@"IDtest",nil];
    [values writeToFile:path atomically:YES];
    [values release];


    [self dismissModalViewControllerAnimated:YES];
}

此代码仅适用于GET请求。 我看到它有很多框架(例如RestKit,....)。 但是我对其他请求感到有些失落! 那么为IOS应用程序发出POST DELETE PUT请求的最佳解决方案是什么?

它是类似的代码,但使用类NSMutableRequest。 您可以设置httpbody和其他参数以与服务器通信。

查看文档: https//developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html

发布一些东西,只需输入setHTTPMethod:@“POST”并使用setHTTPBody将数据分配到post:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM