我写了两个代码都一样
- 使用 NSURLConnection 和
- 使用 AFNetworking。
我的NSURLConnection
代码工作正常,但AFNetworking
代码不行。问题是我从我的NSURLConnection
代码中得到 JSON 响应,但我没有JSON
从AFNetworking
代码中得到响应,但我得到的响应代码为 200。我已经尝试了所有可能的组合,但仍然没有运气。我不知道是什么问题。我想继续使用AFNetworking
,所以请有人帮助我。谢谢你——阿米特
NSURL连接:
- (IBAction)connectHandler:(UIButton *)sender {
//This is where we attempt to connect to the URL represented by self.labelHostURL
//along with exception handling
NSString *request_type = @"STARTUP";
NSString *request_data = @"{\"lstCacheRefDt\":\"10/10/2010\",\"langCd\":\"en_US\",\"timeZn\":\"America/Chicago\",\"brndId\":\"WM\",\"prgmId\":\"WM0012\"}";
NSLog(@"Request: %@", request_data);
NSURL *url = [NSURL URLWithString:[ self.labelHostURL text ]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//NSData *requestData = [NSData dataWithBytes:[request_data UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString* request_body = [NSString
stringWithFormat:@"request_type=%@&request_data=%@",
[request_type stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[request_data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:[request_body dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self]; }
AF网络:
- (void) getHomeData {
NSURL *url = [[NSURL alloc] initWithString:@"https://localhost:8443/MNMMLMockService/mAccountsWeb/services/mnapp/rpc"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *homePostParams1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"10/10/2010", @"lstCacheRefDt",
@"en_US", @"langCd",
@"America/Chicago", @"timeZn",
@"WM", @"brndId",
@"WM0012", @"prgmId", nil];
NSDictionary *homePostParams = [NSDictionary dictionaryWithObjectsAndKeys:@"STARTUP", @"request_type", homePostParams1,@"request_data", nil];
NSLog(@"Dic: %@", homePostParams);
NSMutableURLRequest *homeRequest = [httpClient requestWithMethod:@"POST" path:@"" parameters:homePostParams];
[homeRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[homeRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:homeRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"JSON %@", JSON);
NSLog(@"operation StatusCode: %d", [response statusCode]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start]; }