【发布时间】:2014-11-25 08:27:47
【问题描述】:
我想使用简单的 Objective C 代码方法创建 HTTP 请求 post 和 get 响应。下面的代码我可以成功发布。但我没有收到响应数据。仅响应打印 null 值。请帮帮我,我需要获取响应数据。
在我的代码下面
NSString *post = [NSString stringWithFormat:@"name=%@",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(@"Connection Successful");
} else {
NSLog(@"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:@"response"];
NSLog(@"UPDATE RESPONSE : %@", respon);
【问题讨论】:
-
响应不是有效的 JSON。从 responseData 创建 NSString 并打印出来。同时打印 err 和 error 变量。
-
能否请您发布一些代码?我找不到你。
-
NSLog(@"%@", err);和 NSLog(@"%@", 错误);
-
仅打印(空)@AbhiBeckert
-
不如去谷歌搜索一下如何将 NSData 转换为 NSString?无论如何,这可能是不可能的,因为数据可能不是有效的字符串。这就是我建议改用 HexFiend 的原因。
标签: ios objective-c http nsurlconnection