网络请求 Get & Post 方法(整理)
来源:互联网 发布:销售清单打印机软件 编辑:程序博客网 时间:2024/04/28 23:58
//服务器开始返回数据
// 收到服务器返回的数据,本方法会被调用多次
- (void)connection:didReceiveData:
// 数据接收完毕,做数据的最后处理
// 网络连接错误
- (void)connection:didFailWithError:
// 发送数据给服务器,POST请求使用此方法
- (void)connection:didSendBodyData:totalBytesWritten: totalBytesExpectedToWrite:
POST请求步骤(定义/启动Connection部分省略)
GET请求操作代码
获得服务器数据的准备工作
通过NSURLConnectionDataDelegate代理方法接收数据
// 收到服务器返回数据,本方法会被调用多次
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"收到服务器返回数据%@",data);
[_receivedDataappendData:data];
}
// 数据接收结束
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSString*string = [[NSStringalloc]initWithData:_receivedDataencoding:NSUTF8StringEncoding];
NSLog(@"接收完毕,返回内容为:%@",string);
//释放数据
_receivedData =nil;
}
// 网络连接错误
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
//取消对URL的编码即可发生错误。
NSLog(@"网络连接错误:%@", error.localizedDescription);
}
POST请求操作代码
// 初始化接收数据
_receivedData = [NSMutableDatadata];
// 定义URL,字母及数字组成的url不需要编码
NSURL *url = [NSURLURLWithString:LOGIN_URL];
// 定义请求
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
// 等待服务器响应的最长时间
[request setTimeoutInterval:5.0];
// 设置请求方法,大小写无关
[request setHTTPMethod:@"post"];
NSString *bodyString = [NSStringstringWithFormat:@”username=%@&password=%@",_userNameText.text,_passwordText.text];
// 生成请求体数据并编码
NSData*body = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
// 设置HTTP请求数据体,NSMutableURLRequest会自动在请求头中加入Content-Length
[requestsetHTTPBody:body];
// 定义连接
……
NSURLConnectionDataDelegate代理方法// 发送数据给服务器,POST请求使用此方法
- (void)connection:(NSURLConnection*)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSLog(@“发送数据给服务器bytesWritten:%d,totalBytesWritten %dtotalBytesExpectedToWrite %d”, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
同步请求和异步请求
sendSynchronousRequest:request returningResponse:&responseerror:&error
sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,NSData*data, NSError*error)
有关主操作队列的内容,在多线程课程讲解
- 网络请求 Get & Post 方法(整理)
- 网络请求(get&&post)
- 网络请求(get Post)
- 网络请求的get,post 方法,同步,异步请求
- OKHttp网络请求(get / post)
- HttpURLConection(get¥¥ post)网络请求+XListView
- eclipse中网络设置及get和post请求(get请求或者post请求)
- 简单网络请求/GET请求/POST请求
- http请求方法(GET、POST)
- HttpUrlConnect GET()和POST()方法请求
- HTTP请求接口方法(POST/GET)
- 网络请求,get和post
- Get和post网络请求
- volley网络请求,get/post
- 网络请求方式 POST + GET
- HttpURLConnection,get,post,网络请求
- HttpURLConnection 网络请求 get post
- ios之NSURLConnection网络请求数据/GET与POST方法
- java解惑之Calendar
- Apache ZooKeeper交流
- do...while(0)的妙用
- [POI2000]啤酒厂选址
- 输入一些数,按从小到大排序
- 网络请求 Get & Post 方法(整理)
- 第6周-思维导图-第8、9章知识点
- 【北大先修课】计算概论(A)题库全代码
- UVa 11000 - Bee
- 真正统治世界的十大算法
- 【Java】a=a+b与a+=b的区别
- 关于oracle with as用法
- 适于互联网的SEDA高并发架构
- 生物信息相关国家自然科学基金汇总(持续更新中)