我在这里遇到一个奇怪的问题,并且我没有发现其他人有同样的问题。
我正在使用AFNetworking
制作AFJSONRequestOperation
。
第一次进行网络连接时,它可以正常工作。但是,一旦建立网络连接,相同的代码就会失败,并显示“错误的URL”错误。
奇怪的是,应用程序在失败之前甚至都没有ping服务器,我正在使用Charles来嗅探所有请求。
还有其他人经历过这个吗?
供参考,以下是代码:
NSURL *url = [NSURL URLWithString:JOIN_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// httpClient.parameterEncoding = AFJSONParameterEncoding;
NSString *path = [NSString stringWithFormat:@"%@?%@",JOIN_URL, getString];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:path parameters:nil];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"SUCCESS JSON: %@", JSON);
NSLog(@"RESPONSE URL: %@",response.URL);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"FAIL JSON: %@", JSON);
NSLog(@"FAIL ERROR: %@", error.description);
NSLog(@"RESPONSE URL: %@",response.URL);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error" message:@"Cannot connect now, please try again" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];
[alert show];
}];
[operation start];
答案 0 :(得分:5)
您应该像这样编码您的网址path
字符串:
NSString* escapedUrlString =[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
答案 1 :(得分:5)
据我了解AFHTTPClient
,您为其提供了baseURL
,这是基本网址,您指定的所有路径都将附加到该网址。然后,当您提供路径时,您只提供此路径的相对部分。
因此,如果您的http://www.example.com/webservice/处的WebService有一些方法,例如/listAll?n=10
,那么您只需"listAll"
path
requestWithMethod:path:parameters:
参数@{ @"n" : @10 }
和parameters
参数的字典JOIN_URL
。
无论如何,当您实例化AFHTTPClient
时,您已经提供了JOIN_URL
,因此如果您再次在路径中传递AFHTTPClient
,则会在建立的网址中显示两次内部{{1}}!
答案 2 :(得分:0)
目标-C:
[query stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]];
夫特:
query.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLQueryAllowedCharacterSet())