ios - 尝试用 Objective-C (IOS7) 做一个简单的 JSON 请求

标签 ios json nsurlconnection

我搜索并尝试了许多不同的解决方案,但没有运气。

我正在尝试向我的服务器发出 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");
}

}

委托(delegate) DidReceiveData 正确触发,但结果始终为 NIL:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"RESULT1: %@", jsonResponseData);
[_responseData appendData:data];

}

谢谢,希望有人能帮助我!

最佳答案

非常感谢您的评论,我终于修复了它,之后我决定开始使用 JSON 库 --> https://github.com/stig/json-framework/

这就是我最终获得代码的方式:

//prepare connection
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@user.php", _urlServer]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:@"login" forKey:@"action"];
[data setObject:username forKey:@"username"];
[data setObject:password forKey:@"password"];

//start connection
// Create the request, if there is a connection going on just cancel it.
[_connection cancel];

//initialize new mutable data
NSMutableData *receivedData = [[NSMutableData alloc] init];
_receivedData = receivedData;

//initialize the url which will be fetched
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

//set http method
[request setHTTPMethod:@"POST"];

//initialize a post data
NSString *dataString = [[NSString alloc] init];
for(id key in data) {
    id value = [data objectForKey:key];
    //keys string
    NSString *newData =  [NSString stringWithFormat:@"&%@=%@", key, value];
    dataString = [dataString stringByAppendingString: newData];
}

//set request content type we MUST set this value.
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

//set post data of request
[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];

//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;

//NSLog(@"Sending request with parameters: %@", dataString);

//begin the connection
[_connection start];

它的作用就像一个魅力。下一步是以某种方式进行身份验证,现在连接已向世界开放。

关于ios - 尝试用 Objective-C (IOS7) 做一个简单的 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19097099/

相关文章:

ios - 登录不起作用/卡在最新的 Facebook SDK 中

javascript - 将数组中的相似记录分组为一个键?

java - Jackson 在对丢失的属性(property)进行反序列化期间抛出 NPE

ios - 使用 JSON 的 iOS 谷歌搜索

cocoa - 需要有关 NSURLCredential initWithTrust : 的帮助

ios - 有什么方法可以调用 "fire and forget"API吗?

ios - UILabel 在 iOS7 中有一个奇怪的灰色顶线/边框,我该如何删除它?

ios - iOS 字体名称列表

ios - 带有部分重复单元格的 UITableView

ios - NSURLConnection 异步线程连接关闭