http協議:
http://api.youripapi.com/ip/
https協議:
https://api.youripapi.com/ip/
* API接口可能會因為各種網絡原因和攻擊都可能産生阻斷,請開發時做好冗餘和異常處理
* 當HTTP請求返回的狀態碼非200時,請做異常處理,比如 202 狀態碼造成的原因可能是無效Token、餘額不足、格式錯誤
Android調用iP查詢接口示例:
package com.lmqkk.test;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QueryTask task = new QueryTask();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"8.8.8.8","txt","find","859476648b3de65d76804ff906dd1a1c6a");
} else {
task.execute("8.8.8.8","txt","find","859476648b3de65d76804ff906dd1a1c6a");
}
}
class QueryTask extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... strings) {
String strUrl = "https://api.youripapi.com/ip/" ;
Map<String,String> params = new HashMap<String,String>();
params.put("ip",strings[0]); //可為空
params.put("datatype",strings[1]);
params.put("callback",strings[2]); //可為空
String result = null;
try {
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//頭信息
HashMap<String, String> header = new HashMap<String,String>();
header.put("token", strings[3]);
for (String headerName : header.keySet()) {
connection.addRequestProperty(headerName, header.get(headerName));
}
//設置超時時間
connection.setConnectTimeout(5*1000);
//設置允許輸入
connection.setDoInput(true);
//設置讀取超時:
connection.setReadTimeout(5*1000);
connection.setRequestMethod("GET");
//參數
byte[] body = encodeParameters(params,"UTF-8");
if (body != null)
{
connection.setDoOutput(true);
connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + "UTF-8");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(body);
out.close();
}
int responseCode = connection.getResponseCode();
if (responseCode == -1) {
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
if (responseCode != 200)
{
return responseCode + "";
}
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray(), "UTF-8");
}
catch (IOException e) {
e.printStackTrace();
}
}
return result;
}catch(SocketTimeoutException e)
{
}catch (MalformedURLException e) {
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Query", "onPostExecute: "+s);
}
byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
if (params == null || params.size() == 0) return null;
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
}
}