簡體   English   中英

來自iOS的http請求

[英]http request from iOS

我正在嘗試向發送請求

"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}

碼:

    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];

謝謝

您的問題很可能取決於您的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);
}

這樣吧

首先,創建一個字符串來存儲字符串

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM