http request from iOS
-
21-12-2019 - |
質問
I am trying to send a request to
"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/"
which returns a JSON.
Pasting the address in my browser returns a JSON, I just don't know how to do it in iOS
I tried the following in AFNetworking, but the return was:
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14930080 {
NSUnderlyingError=0x14753ac0 "bad URL", NSLocalizedDescription=bad URL}
code:
url = [NSURL URLWithString:"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation , id responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
// code
}];
[operation start];
Thanks
解決
Your problem most likely relies on your URL. All URLs used in NSURLRequest should be escaped. Try to escape your URL before using it:
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];
他のヒント
Use Following code for request,
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];
And get response in following code,
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableDictionary* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:nil];
NSLog(@"json===%@",json);
}
Do like this,
First, create a string to store the string
NSString *strigURL=[NSString stringWithFormat:@"http://www.geocodefarm.com/api/forward/json/f0e3d8f953e83ca08c1eb487c64f9b3ecc379d5c/530 W Main St Anoka MN 55303 US/"];
Initialise an object for NSURL
NSURL *url=[NSURL URLWithString:strigURL];
To request
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError *error;
NSURLResponse * response;
the data received from response
NSData * responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Encoded data
output=[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"Response : %@",output);
所属していません StackOverflow