http協議:
http://api.youripapi.com/ip/
https協議:
https://api.youripapi.com/ip/
* API接口可能會因為各種網絡原因和攻擊都可能産生阻斷,請開發時做好冗餘和異常處理
* 當HTTP請求返回的狀態碼非200時,請做異常處理,比如 202 狀態碼造成的原因可能是無效Token、餘額不足、格式錯誤
Object-C(ios)語言調用iP查詢接口示例:
//
// ViewController.m
// ApiTest
//
// Created by administrator on 16/9/8.
// Copyright © 2016年 star. All rights reserved.
//
#import "ViewController.h"
#define Host @"https://api.youripapi.com/ip/"
@interface ViewController ()<NSXMLParserDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString * token = @"859476648b3de65d7680494506dd1a1c6a";
[self executeNetworkWithIP:@"8.8.8.8" dateType:@"xml" callBack:@"" token:token];
}
/**
*示例https://api.youripapi.com/ip/?ip=8.8.8.8&datatype=jsonp&callback=&token=859476648b3de65d7680494506dd1a1c6a
*參數說明:
*1. ip string ip地址 例如 117.25.13.123(可選,默認為請求者iP)
*2. datatype string txt|jsonp|xml(可選,默認為jsonp)
*3. callback string 回調函數 當前參數僅為jsonp格式數據提供(可選,默認為空)
*4. token string 購買服務後會提供(必填)
*/
- (void)executeNetworkWithIP:(NSString *)ip dateType:(NSString *)dateType callBack:(NSString *)callBack token:(NSString *)token{
NSString * urlString =[NSString stringWithFormat:@"%@?ip=%@&datatype=%@&callback=%@&token=%@",Host,ip,dateType,callBack,token];
//準備網絡請求
NSString *newStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:newStr];
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
//請求異步鏈接
[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(@"jsonError = %@",connectionError);
return ;
}
//請求格式txt
if ([dateType isEqualToString:@"txt"]) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result = %@",result);
}
//datatype xml
else if ([dateType isEqualToString:@"xml"]){
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result = %@",result);
}
else{
NSError *jsonError = nil;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
/*如果設置了回調函數,則可截取後再在轉化為NSDictionary,也可直接轉化為NSString*/
if (callBack&&[callBack length]>0) {
NSRange range = [jsonString rangeOfString:@"("];
range.location++;
range.length = [jsonString length] - range.location - 1;
jsonString = [jsonString substringWithRange:range ];
}
NSDictionary *jsonResponse =
[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if (jsonError) {
NSLog(@"jsonError = %@",jsonError);
return ;
}
NSLog(@"jsonResponse = %@",jsonResponse);
}
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end