iOS json登录服务器

来源:互联网 发布:教育部网络培训中心 编辑:程序博客网 时间:2024/06/06 09:32

1.导入JSONKit.h JSONKit.m

2.ViewController.m中引用头文件 

#import "JSONKit.h"

3.

登录按钮中写:

- (IBAction)login:(UIButton *)sender {

        NSString *urlString =@"http:……"

       NSURL *url = [NSURLURLWithString:urlString];

        NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

        [requestsetTimeoutInterval:5.0];

        [requestsetHTTPMethod:@"post"];

 NSString *bodyString =@"发送内容一般是有格式的用户名和密码";

        NSData *body = [bodyStringdataUsingEncoding:NSUTF8StringEncoding];

       NSLog(@"bodystring %@", bodyString);

        [requestsetHTTPBody:body];

       NSURLConnection *conn = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];

        [connstart]; 

    }

}

4.下列函数写入ViewController.m,与- (void)viewDidLoad 并列

#pragma mark - 连接代理方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"开始接受服务器的返回请求");

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    NSLog(@"1111111");

    _serverData = [NSMutableDatadata];

    [_serverDataappendData:data];    

   NSLog(@"中间接收的数据:%@", data);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSString *string = [[NSStringalloc]initWithData:_serverDataencoding:NSUTF8StringEncoding];

    NSError *error =nil;


    id jsonObject = [NSJSONSerializationJSONObjectWithData:_serverDataoptions:NSJSONReadingAllowFragmentserror:&error];

    


   if (jsonObject != nil && error == nil)

    {

        NSLog(@"Successfully deserialized...");

       if ([jsonObject isKindOfClass:[NSDictionaryclass]])

        {

           NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;

           NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);

        }

    }

}


// 网络请求失败

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"失败 %@", error.localizedDescription);

    _serverData = nil;

}


- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite

{

   NSLog(@"发送数据 %ld %ld %ld", (long)bytesWritten, (long)totalBytesWritten, (long)totalBytesExpectedToWrite);

}

5.结束 测试




0 0