您的位置:首页 > 移动开发 > IOS开发

iOS json登录服务器

2015-06-08 13:15 501 查看
1.导入JSONKit.h JSONKit.m

2.ViewController.m中引用头文件

#import "JSONKit.h"
3.

登录按钮中写:
- (IBAction)login:(UIButton *)sender {

NSString *urlString =
@"http:……";

NSURL *url = [NSURL
URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];
[request
setTimeoutInterval:5.0];
[request
setHTTPMethod:@"post"];


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

NSData *body = [bodyString
dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"bodystring %@", bodyString);
[request
setHTTPBody:body];

NSURLConnection *conn = [[NSURLConnection
alloc]initWithRequest:request
delegate:self];
[conn
start];
}
}
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 = [NSMutableData
data];
[_serverData
appendData:data];

NSLog(@"中间接收的数据:%@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

NSString *string = [[NSString
alloc]initWithData:_serverData
encoding:NSUTF8StringEncoding];

NSError *error =
nil;

id jsonObject = [NSJSONSerialization
JSONObjectWithData:_serverData
options:NSJSONReadingAllowFragments
error:&error];




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

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

if ([jsonObject isKindOfClass:[NSDictionary
class]])
{

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.结束 测试
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: