今天需要用到put请求方式请求数据,然而用AFNetWorking进行put请求许久没有成功,加上网络上的资源很少,以为没有办法实现了。后来却又是柳暗花明又一村,用iOS原生的方法就可以实现请求,发现自己舍本逐末了。
这是自己封装的,urlStr是地址,paramStr请求需要的参数,headers需要带的请求头(这里用作标记是否有请求头)。
代码如下:
+ (void)putRequest:(NSString *)urlStr paramDic:(id)paramStr header:(NSDictionary*)headers finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
NSString *url = urlStr;
//初始化请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//设置请求类型
[request setHTTPMethod:@"PUT"];
[request setURL:[NSURL URLWithString:url]];
/********根据自己的情况设置header,这里取固定的数据传给请求**************/
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *person = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"cookie"]];
NSDictionary *token = person[@"token"];
NSDictionary *users = person[@"user"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[users[@"user_id"] stringValue] forHTTPHeaderField:@"X-User-Id"];
[request setValue:users[@"user_name"] forHTTPHeaderField:@"X-User-Name"];
[request setValue:users[@"user_nick"] forHTTPHeaderField:@"X-User-Nick"];
[request setValue:@"distributor" forHTTPHeaderField:@"X-User-Type"];
[request setValue:[NSString stringWithFormat:@"%@ %@",token[@"token_type"],token[@"access_token"]] forHTTPHeaderField:@"Authorization"];
//设置需要传递的参数 paramStr要拼接成字符串
NSData *postData = [paramStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
// 绑定返回数据或错误
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
enError (error);
return ;
}
NSString *requestReply = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSDictionary *resDic = [CommonTools dictionaryWithJsonString:requestReply];
finish(resDic[@"data"]);
}
代码截图:
结果: