来自iOS的http请求

来自iOS的http请求,ios,json,ios6,httprequest,afnetworking,Ios,Json,Ios6,Httprequest,Afnetworking,我正试图向您发送请求 "http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/" which returns a JSON. 在我的浏览器中粘贴地址会返回一个JSON,我只是不知道如何在iOS中这样做 我在AFNetworking中尝试了以下方法,但结果是: Error Domain=NSURLErrorDomain

我正试图向您发送请求

"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/"
which returns a JSON.
在我的浏览器中粘贴地址会返回一个JSON,我只是不知道如何在iOS中这样做

我在AFNetworking中尝试了以下方法,但结果是:

Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14930080 {
NSUnderlyingError=0x14753ac0 "bad URL", NSLocalizedDescription=bad URL}
代码:

谢谢

像这样做

首先,创建一个字符串来存储该字符串

NSString *strigURL=[NSString stringWithFormat:@"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/"];  
初始化NSURL的对象

NSURL *url=[NSURL URLWithString:strigURL];  
请求

NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError *error;
NSURLResponse * response;  
从响应接收的数据

NSData * responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  
编码数据

 output=[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"Response : %@",output);

您的问题很可能与您的URL有关。应转义NSURLRequest中使用的所有URL。在使用URL之前,请尝试将其转义:

NSString* yourURLString = @"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/";
NSString* escapedUrlString =[yourURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url = [NSURL URLWithString:escapedUrlString];

使用以下代码进行请求

NSString *aStr=@"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/";
NSString* aStrFinal =[aStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *aUrl=[NSURL URLWithString:aStrFinal];
NSURLRequest *aREquest=[NSURLRequest requestWithURL:aUrl];
[NSURLConnection connectionWithRequest:aREquest delegate:self];
并在下面的代码中得到响应

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

NSMutableDictionary* json = [NSJSONSerialization
                        JSONObjectWithData:data //1

                        options:kNilOptions
                        error:nil];
  NSLog(@"json===%@",json);
}

同步请求是错误的。每次你使用一只小猫时,上帝都会杀死一只小猫。@Cyrille,请告诉我这会发生什么。整个应用程序将被完全冻结,直到DNS名称被解析,连接被打开,请求被发送到服务器,服务器处理请求,你的设备接收返回的数据。这可能需要相当长的时间。同步请求从来都不是正确的解决方案。哦,所以我应该始终使用异步请求。这甚至不应该是一个问题。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

NSMutableDictionary* json = [NSJSONSerialization
                        JSONObjectWithData:data //1

                        options:kNilOptions
                        error:nil];
  NSLog(@"json===%@",json);
}