// RequestHeader.h
// TangYS
//
// Created by TangYS
#import <Foundation/Foundation.h>
@interface RequestHeader : NSObject {
}
@property (nonatomic,copy) NSString *requestMethod;
@property (nonatomic, copy) NSString *uuid;
@property (nonatomic, copy) NSString *ua;
@property (nonatomic, copy) NSString *ip;
@property (nonatomic, copy) NSString *nettype;
@property (nonatomic, copy) NSString *model;
@property (nonatomic, copy) NSString *device;
@property (nonatomic, copy) NSString *mANUFACTURER;
@property (nonatomic, strong) NSString *m_operator;
@property (nonatomic, strong) NSString *userId;
@property (nonatomic, copy) NSString *USER;
@property (nonatomic, copy) NSString *CLIENT_VERSION;
@property (nonatomic, copy) NSString *Product;
@property (nonatomic, copy) NSString *CPU_ABI;
@property (nonatomic, copy) NSString *TAGS;
@property (nonatomic, copy) NSString *VERSION_CODES_BASE;
@property (nonatomic, copy) NSString *VERSION_RELEASE;
@property (nonatomic, copy) NSString *sdk;
@property (nonatomic, copy) NSString *DISPLAY;
@property (nonatomic, copy) NSString *BRAND;
@property (nonatomic, copy) NSString *BOARD;
@property (nonatomic, copy) NSString *FINGERPRINT;
@property (nonatomic, copy) NSString *mID;
@property (nonatomic, copy) NSMutableDictionary *infoDic;
-(void)packageHeader:(NSMutableURLRequest *) mPostData;
+(RequestHeader *) sharedInstance;
@end
//
// RequestHeader.m
// Ocj
//
// Created by ocjwork on 11-12-30.
// Copyright 2011 ocj. All rights reserved.
//
#import "RequestHeader.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "MyMD5.h"
#import "SvUDIDTools.h"
#import "Reachability.h"
#import "ASIFormDataRequest.h"
#import "GetUA.h"
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
@interface RequestHeader (){
}
-(NSString*)carrierName;
@end
@implementation RequestHeader
static RequestHeader *sharedInstance=nil;
+(RequestHeader *) sharedInstance{
@synchronized(self){
if(!sharedInstance)
{
sharedInstance =[[RequestHeader alloc]init];
}
return sharedInstance;
}
}
-(void)packageHeader:(NSMutableURLRequest *) urlRequest{
//獲得info.plist文件中的配置信息
[urlRequest setHTTPMethod:@"POST"];
NSLog(@"%@",[self getUUID]);
_uuid = [self getUUID]; //@"UUID"
_ua = @"";//@"UA"
_ip = [self localIPAddress];//IP
_nettype = [self netWorkConnectionIsNormal]; //NETTYPE
_model = [self getModel];//MODEL
_device = [self getDevice];//DEVICE
_mANUFACTURER = [self manufacturer];//MANUFACTURER
_m_operator = [self carrierName];
NSString *uId=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"]];
_userId = uId;//USERID
_USER = @"";//USER
_CLIENT_VERSION =@"1.1.1";//CLIENT_VERSION
_Product = @"";//Product
_CPU_ABI = @"";//CPU_ABI
_TAGS = @"";//TAGS
_VERSION_CODES_BASE =@"";//VERSION_CODES.BASE
_VERSION_RELEASE = @"";//VERSION.RELEASE
_sdk = @"";//SDK
_DISPLAY = @"";//DISPLAY
_BRAND = @"";//BRAND
_BOARD = @"";//BOARD
_FINGERPRINT = @"";//FINGERPRINT
_mID = @"";//ID
// _infoDic = [NSMutableDictionary dictionary];
[urlRequest setValue:_uuid forHTTPHeaderField:@"UUID"];
[urlRequest setValue:_ua forHTTPHeaderField:@"UA"];
[urlRequest setValue:_ip forHTTPHeaderField:@"IP"];
[urlRequest setValue:_nettype forHTTPHeaderField:@"NETTYPE"];
[urlRequest setValue:_model forHTTPHeaderField:@"MODEL"];
[urlRequest setValue:_device forHTTPHeaderField:@"DEVICE"];
[urlRequest setValue:_mANUFACTURER forHTTPHeaderField:@"MANUFACTURER"];
[urlRequest setValue:_m_operator forHTTPHeaderField:@"Operator"];
[urlRequest setValue:_userId forHTTPHeaderField:@"USERID"];
[urlRequest setValue:_USER forHTTPHeaderField:@"USER"];
[urlRequest setValue:_CLIENT_VERSION forHTTPHeaderField:@"CLIENT_VERSION"];
[urlRequest setValue:_Product forHTTPHeaderField:@"Product"];
[urlRequest setValue:_CPU_ABI forHTTPHeaderField:@"CPU_ABI"];
[urlRequest setValue:_TAGS forHTTPHeaderField:@"TAGS"];
[urlRequest setValue:_VERSION_CODES_BASE forHTTPHeaderField:@"VERSION_CODES.BASE"];
[urlRequest setValue:_VERSION_RELEASE forHTTPHeaderField:@"VERSION.RELEASE"];
[urlRequest setValue:_sdk forHTTPHeaderField:@"SDK"];
[urlRequest setValue:_DISPLAY forHTTPHeaderField:@"DISPLAY"];
[urlRequest setValue:_BRAND forHTTPHeaderField:@"BRAND"];
[urlRequest setValue:_BOARD forHTTPHeaderField:@"BOARD"];
[urlRequest setValue:_FINGERPRINT forHTTPHeaderField:@"FINGERPRINT"];
[urlRequest setValue:_mID forHTTPHeaderField:@"ID"];
// [postData setRequestMethod:@"POST"];
// NSLog(@"%@",[self getUUID]);
// [postData addRequestHeader:@"UUID" value:[self getUUID]];
// [postData addRequestHeader:@"UA" value:@""];
// [postData addRequestHeader:@"IP" value:[self localIPAddress]];
// [postData addRequestHeader:@"NETTYPE" value:[self netWorkConnectionIsNormal]];
// [postData addRequestHeader:@"MODEL" value:[self getModel]];
// [postData addRequestHeader:@"DEVICE" value:[self getDevice]];
// [postData addRequestHeader:@"MANUFACTURER" value:[self manufacturer]];
// [postData addRequestHeader:@"Operator" value:[self carrierName]];
// [postData addRequestHeader:@"USERID" value:uId];
// [postData addRequestHeader:@"USER" value:@""];
// [postData addRequestHeader:@"CLIENT_VERSION" value:@"1.1.1"];
// [postData addRequestHeader:@"Product" value:@""];
// [postData addRequestHeader:@"CPU_ABI" value:@""];
// [postData addRequestHeader:@"TAGS" value:@""];
// [postData addRequestHeader:@"VERSION_CODES.BASE" value:@""];
// [postData addRequestHeader:@"VERSION.RELEASE" value:@""];
// [postData addRequestHeader:@"SDK" value:@""];
// [postData addRequestHeader:@"DISPLAY" value:@""];
// [postData addRequestHeader:@"BRAND" value:@""];
// [postData addRequestHeader:@"BOARD" value:@""];
// [postData addRequestHeader:@"FINGERPRINT" value:@""];
// [postData addRequestHeader:@"ID" value:@""];
}
-(NSString *)getUUID{
NSString *udid = [SvUDIDTools UDID];
/*
<36383a35 423a3335 3a44313a 31323a34 30>//初次啓動
<36383a35 423a3335 3a44313a 31323a34 30>//登錄
<36383a35 423a3335 3a44313a 31323a34 30>
<36383a35 423a3335 3a44313a 31323a34 30>//更多
<36383a35 423a3335 3a44313a 31323a34 30>//患者
*/
NSLog(@"udid in keychain %@", udid);
/*
keychain 68:5B:35:D1:12:40
keychain 68:5B:35:D1:12:40
keychain 68:5B:35:D1:12:40
keychain 68:5B:35:D1:12:40
keychain 68:5B:35:D1:12:40
*/
NSLog(@"current identityForVendor %@", [UIDevice currentDevice].identifierForVendor);
return [MyMD5 md5:udid];
}
//ip
//- (NSString *)getCurrentIP
//{
// NSError *error;
// NSURL *ipURL = [NSURL URLWithString:@"http://www.whatismyip.com.tw/"];
// NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
// return ip;
//}
- (NSString *)localIPAddress
{
NSString *localIP = nil;
struct ifaddrs *addrs;
if (getifaddrs(&addrs)==0) {
const struct ifaddrs *cursor = addrs;
while (cursor != NULL) {
if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
{
//NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
//if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
{
localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
break;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return localIP;
}
// NETTYPE
-(NSString *)netWorkConnectionIsNormal
{
Reachability *r=[Reachability reachabilityWithHostName:@"www.apple.com"];
// BOOL isNormal;
switch ([r currentReachabilityStatus]) {
case NotReachable:
NSLog(@"FORMListViewcontroller無網絡" );
// 沒有網絡連接
// NSLog(@"沒有網絡");
// isNormal = NO;
break;
case ReachableViaWWAN:
NSLog(@"FORMListViewcontroller正在使用3G網絡");
// 使用3G網絡
// NSLog(@"正在使用3G網絡");
return @"3G";
case ReachableViaWiFi:
NSLog(@"FORMListViewcontroller正在使用wifi網絡" );
// 使用WiFi網絡
// NSLog(@"正在使用wifi網絡");
return @"Wifi";
}
return @"";
}
//Product
//DISPLAY
//BRAND
//BOARD
//FINGERPRINT
//ID
//CPU_ABI
//VERSION_CODES.BASE
//SDK
//VERSION.RELEASE
//CLIENT_VERSION:客戶端版本號
//USER
//MODEL
//USERID:用戶ID(如此項有值則填正確的用戶ID,如果是用戶註冊、登錄等還未獲得用戶ID的情況則該項值填0)
-(NSString *)getModel{
// //手機型號
NSString* phoneModel = [[UIDevice currentDevice] model];//4
if(nil==phoneModel){
return nil;
}
return phoneModel;//手機型號
}
//DEVICE
-(NSString *)getDevice{
//系統版本
UIDevice* device = [UIDevice currentDevice];//3
device.batteryMonitoringEnabled = YES;
NSMutableString* systemNameAndVersion = [NSMutableString stringWithString:[device systemName]];
[systemNameAndVersion appendFormat:@" %@", [device systemVersion]];
return systemNameAndVersion;
}
//MANUFACTURER製造商
-(NSString *)manufacturer{
return @"apple";
}
//Operator:運營商編號
-(NSString*)carrierName
{
CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [netInfo subscriberCellularProvider];
NSString *carrierCode;
if (carrier == nil) {
carrierCode = @"WiFi";
}
else {
carrierCode = [carrier carrierName];
}
return carrierCode;
}
@end
*******************************************************************************************************************************
//
// RequestHelper.h
// TangYS
//
// Created by hsdtkj on 14-8-27.
// Copyright (c) 2014年 ___HSDT___. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RequestHeader.h"
//view <-> service <-> helper
//網絡 請求
/*
service是把你 View 裏面的數據拿來傳給 helper 然後處理返回數據在返回給 view
*/
static NSOperationQueue *queue;
@interface RequestHelper : NSObject<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
{
NSMutableURLRequest *urlRequest;
RequestHeader *header;
NSMutableData *mutableData;
}
@property (nonatomic, assign) id delegate;
@property (assign) SEL requestFinishedSelector;
@property (assign) SEL requestFailedSelector;
@property (nonatomic, strong)NSMutableURLRequest *urlRequest;
@property (nonatomic, strong)RequestHeader *postHeader;
-(void)postRequestPath:(NSString *)path params:(NSDictionary *)params;
@end
//
// RequestHelper.m
// TangYS
//
// Created by hsdtkj on 14-8-27.
// Copyright (c) 2014年 ___HSDT___. All rights reserved.
//
#import "RequestHelper.h"
#import "RequestHeader.h"
#import "AFURLRequestSerialization.h"
#import "AFURLConnectionOperation.h"
@implementation RequestHelper
@synthesize urlRequest,postHeader;
@synthesize requestFailedSelector;
@synthesize requestFinishedSelector;
@synthesize delegate;
-(void)postRequestPath:(NSString *)path params:(NSDictionary *)params{
queue = [NSOperationQueue mainQueue];
/* 打包 header */
//...
self.urlRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
self.postHeader=[[RequestHeader alloc]init];
[self.postHeader packageHeader:self.urlRequest];
NSMutableData *tempJsonData=[[NSMutableData alloc]initWithData:[[NSJSONSerialization jsonStringWithJSONObject:params]dataUsingEncoding:NSUTF8StringEncoding]];
[self.urlRequest setHTTPBody:tempJsonData];
[NSURLConnection sendAsynchronousRequest:self.urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,NSData *data,NSError *error) {
if ([data length] > 0 && error == nil)
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//操作
NSDictionary *rotDictionary=[NSJSONSerialization toArrayOrNSDictionaryWithJsonstring:responseString];
if (delegate && [delegate respondsToSelector:requestFinishedSelector]) {
[delegate performSelector:requestFinishedSelector withObject:rotDictionary];
}
}
else if ([data length] == 0 && error ==nil)
{
//沒有數據
}
else if (error != nil)
{
NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
//超時
if (delegate && [delegate respondsToSelector:requestFailedSelector]) {
[delegate performSelector:requestFailedSelector withObject:(NSString *)error];
}
}
else
{
NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
}
}];
}
// if(urlConnection){
// self.mutableData=[NSMutableData data];
// }else{
// BBLog(@"創建網絡失敗");
// }
//參數cachePolicy表示緩存策略,枚舉類型,值有以下幾種:
//
//enum
//{
// NSURLRequestUseProtocolCachePolicy = 0 NSURLRequest默認的cache policy,使用Protocol協議定義。是最能保持一致性的協議。
// NSURLRequestReloadIgnoringCacheData = 1 忽略緩存直接從原始地址下載 = NSURLRequestReloadIgnoringCacheData
// NSURLRequestReturnCacheDataElseLoad = 2 只有在cache中不存在data時才從原始地址下載
// NSURLRequestReturnCacheDataDontLoad = 3 只使用cache數據,如果不存在cache,請求失敗;用於沒有建立網絡連接離線模式;
// NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4, 忽略本地和遠程的緩存數據,直接從原始地址下載,與NSURLRequestReloadIgnoringCacheData類似。
// NSURLRequestReloadRevalidatingCacheData = 5 驗證本地數據與遠程數據是否相同,如果不同則下載遠程數據,否則使用本地數據。
// };
// typedef NSUInteger NSURLRequestCachePolicy;
/*
// 收到迴應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"receive the response");
// 注意這裏將NSURLResponse對象轉換成NSHTTPURLResponse對象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(@"allHeaderFields: %@",dictionary);
}
[receivedData setLength:0];
}
// 接收數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"get some data");
[receivedData appendData:data];
}
// 數據接收完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *results = [[NSString alloc]
initWithBytes:[receivedData bytes]
length:[receivedData length]
encoding:NSUTF8StringEncoding];
NSLog(@"connectionDidFinishLoading: %@",results);
}
// 返回錯誤
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed: %@", error);
}
*/
//#pragma mark -
//#pragma mark 請求返回
//-(void)requestFinished:(ASIHTTPRequest *)request {
// NSString *ser=[request responseString] ;
// NSDictionary *rotdic=[ser objectFromJSONString ];
// NSString *errMsg=[rotdic objectForKey:@"errMsg"];
// if (![publicClass unNull:errMsg]) {//不是空
// [publicClass dismissProgressHUDErrorWithStatus:errMsg];
//
// if (delegate && [delegate respondsToSelector:requestFinishedSelector]) {
// [delegate performSelector:requestFinishedSelector withObject:rotdic];
// }
// }else{
// NSError *error=[request error];
// if (delegate && [delegate respondsToSelector:requestFailedSelector]) {
// [delegate performSelector:requestFailedSelector withObject:(NSString *)error];
// }
// }
//}
//
//#pragma mark -
//#pragma mark 請求失敗,可能是連接失敗
//-(void)requestFailed:(ASIHTTPRequest *)request {
// [request cancel];
// // [LoadingView showLoadingView:@"服務器正忙請稍後再試!"];
// NSError *error = [request error];
// NSLog(@"%@",(NSString *)error) ;
// // [publicClass showErrorLoading:(NSString *)error];
//
// if (delegate && [delegate respondsToSelector:requestFailedSelector]) {
// [delegate performSelector:requestFailedSelector withObject:(NSString *)error];
// }
//}
@end
*******************************************************************************************************************************************************************
//
// RequestService.h
// TangYS
//
// Created by hsdtkj on 14-8-27.
// Copyright (c) 2014年 ___HSDT___. All rights reserved.
//
#import "RequestHelper.h"
@class RequestHelper;
@class RequestService;
static int seriviceTag;
@interface RequestService : RequestHelper
{
RequestHelper *requestHelper;
}
@property(nonatomic,strong)void(^callSucessBackVC)(id);
@property(nonatomic,strong)void(^callFailedBackVC)(void);
@property(nonatomic,strong)RequestHelper *requestHelper;
-(void)sendRequest:(NSMutableDictionary *)postDic requestTag:(int)tag;
@end
//
// RequestService.m
// TangYS
//
// Created by hsdtkj on 14-8-27.
// Copyright (c) 2014年 ___HSDT___. All rights reserved.
//
#import "RequestService.h"
@implementation RequestService
@synthesize delegate;
@synthesize requestHelper;
- (id)init {
self = [super init];
if (self){
RequestHelper *tempRequest =[[RequestHelper alloc] init];
self.requestHelper = tempRequest;
}
return self;
}
-(void)sendRequest:(NSMutableDictionary *)postDic requestTag:(int)tag {
self.requestHelper.delegate=self;
seriviceTag=tag;
self.requestHelper.requestFinishedSelector = @selector(requestFinish:);
self.requestHelper.requestFailedSelector = @selector(requestFailed:);
[self.requestHelper postRequestPath:MAINURL params:postDic];
}
- (void)requestFinish:(NSDictionary *)body {
NSString *errMsg=[body objectForKey:@"errMsg"];
if ([[body objectForKey:@"code"]intValue]==18) {
[publicClass dismissProgressHUDErrorWithStatus:errMsg];
[publicClass quitApp];
}else{
[publicClass dismissProgressImmediately];
if (seriviceTag==TAG_ACTID_LOGIN) {
[[NSUserDefaults standardUserDefaults]setObject:[body objectForKey:@"userId"] forKey:@"userId"];
}
if (self.callSucessBackVC) {
self.callSucessBackVC(body);
}
}
}
- (void)requestFailed:(NSDictionary *)body{
if (self.callFailedBackVC) {
self.callFailedBackVC();
}
[publicClass dismissProgressHUDErrorWithStatus:@"加載失敗"];
}
@end
*******************************************************************************************************************************************************************
service=[[RequestService alloc]init];
[publicClass showProgressHUDWithStatus:@"登錄中"];
void (^requestSucessBlock)(NSDictionary *)=^(NSDictionary *jsonDictonary){
self.loginBtn.enabled=YES;
NSString *errMsg=[jsonDictonary objectForKey:@"errMsg"];
if ([publicClass unNull:errMsg]) {//不是空
self.tiShiLbl.text= errMsg;
}else{
[[NSUserDefaults standardUserDefaults]setObject:self.userKey.text forKey:@"currentPhone"];
if (![self.sampleStrings containsObject:self.userKey.text]) {
[self.sampleStrings addObject:self.userKey.text];
[[NSUserDefaults standardUserDefaults]setObject:self.sampleStrings forKey:@"phoneCount"];
}
UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
MainTabbarController *vc=(MainTabbarController *)[sb instantiateViewControllerWithIdentifier:@"MainTabbarControllerSb"];
vc.userId=[[jsonDictonary objectForKey:@"userId"] stringValue];
[self.navigationController pushViewController:vc animated:YES];
BBLog(@"%@",jsonDictonary);
}
};
void (^requestFailedBlock)()=^{
self.loginBtn.enabled=YES;
self.tiShiLbl.text=@"加載失敗";
};
[service setCallSucessBackVC:requestSucessBlock];
[service setCallFailedBackVC:requestFailedBlock];
[service sendRequest:postDic requestTag:TAG_ACTID_LOGIN];