我搜索并尝试了许多不同的解决方案,但没有运气。
我正在尝试向我的服务器发出 JSON 请求,它肯定可以工作,因为我已经在 PHP 中对其进行了测试(简单调用,它接收字符串名称和字符串密码,如果用户正确,它会检查数据库)。请求应仅接收带有属性“success”的 JSON(可以是“true”或“false”)。
这是我的代码:
- (void)logonService:(NSString *) name widthArg2:(NSString *) password {
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://46.51.169.145/ios/index.php/user/login/"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
//setting json fields
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//prepare output data
NSString *in1;
NSDictionary *outputData = [NSDictionary dictionaryWithObjectsAndKeys:in1, @"success", nil];
NSError *error = nil;
NSData *jsonOutputData = [NSJSONSerialization dataWithJSONObject:outputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonOutputString = [[NSString alloc] initWithData:jsonOutputData encoding:NSUTF8StringEncoding];
//set json string to body data
NSData *requestInputBodyData = [jsonOutputString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestInputBodyData];
//prepare input data
NSString *input = [NSString stringWithFormat:@"&name=%@&password=%@",name,password];
//Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *inputData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//calculate length of post data
NSString *inputLength = [NSString stringWithFormat:@"%d",[inputData length]];
//Set HTTP header field with length of the post data.
[request setValue:inputLength forHTTPHeaderField:@"Content-Length"];
//encode type
//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
//add it to http body
[request setHTTPBody:inputData];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
NSLog(@"Connection Successful");
}else{
NSLog(@"Connection could not be made");
}
}
委托 DidReceiveData 正确触发,但结果始终为 NIL:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"RESULT1: %@", jsonResponseData);
[_responseData appendData:data];
}
谢谢,希望有人可以帮助我!