我的博客html
簡單記錄集成阿里雲HTTPDNS服務的過程android
HTTPDNS是面向多端應用(移動端APP,PC客戶端應用)的域名解析服務,具備域名防劫持、精準調度、實時解析生效的特性。git
以上來自阿里雲HTTPDNS文檔。github
HTTPDNS是移動研發平臺提供的服務,請參考EMAS 快速入門開通服務。api
完成添加產品後,點擊添加應用,如圖所示網絡
添加應用完成後,點擊剛纔添加的應用app
查看Account ID,這個id後面配置dns會用到異步
在域名列表中添加域名maven
allprojects { repositories { maven { url 'http://maven.aliyun.com/nexus/content/repositories/releases/' } } }
dependencies { compile ('com.aliyun.ams:alicloud-android-httpdns:1.3.3@aar') { transitive true } }
按照以上官方文檔配置,在同步工程後,會報錯
Could not find com.aliyun.ams:alicloud-android-utdid:1.1.5.4. Searched in the following locations: - http://maven.aliyun.com/nexus/content/repositories/releases/com/aliyun/ams/alicloud-android-utdid/1.1.5.4/alicloud-android-utdid-1.1.5.4.pom - https://dl.google.com/dl/android/maven2/com/aliyun/ams/alicloud-android-utdid/1.1.5.4/alicloud-android-utdid-1.1.5.4.pom - https://jcenter.bintray.com/com/aliyun/ams/alicloud-android-utdid/1.1.5.4/alicloud-android-utdid-1.1.5.4.pom Required by: project :app > com.aliyun.ams:alicloud-android-httpdns:1.3.3 > com.aliyun.ams:alicloud-android-beacon:1.0.4.3
修改以下
implementation('com.aliyun.ams:alicloud-android-httpdns:1.3.3@aar') { transitive true exclude group: 'com.aliyun.ams', module: 'alicloud-android-utdid' } implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3'
引入Retrofit及gson
增長依賴
implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.google.code.gson:gson:2.8.6'
配置DNS
新建一個類,繼承Dns
public class AliDns implements Dns { private HttpDnsService httpDns; public AliDns(Context context) { //傳入account_id,account_id爲HTTPDNS控制檯添加應用時生成的 httpDns = HttpDns.getService(context, "account_id"); } @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException { //經過異步解析接口獲取ip String ip = httpDns.getIpByHostAsync(hostname); //Android9.0系統及之後版本,https請求沒法直接訪問,方便起見,直接在AndroidManifest.xml中配置android:usesCleartextTraffic="true" if (ip != null) { //若是ip不爲null,直接使用該ip進行網絡請求 Log.e("AliDns", "ip:" + ip); List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip)); return inetAddresses; } //若是返回null,走系統DNS服務解析域名 return Dns.SYSTEM.lookup(hostname); } }
設置OkHttpClient的dns
OkHttpClient client = new OkHttpClient.Builder().dns(new AliDns(getApplicationContext())).build();
調用請求
Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("域名").addConverterFactory(GsonConverterFactory.create()).build(); Api api = retrofit.create(Api.class); Call<Bean> call = api.getBanner(); call.enqueue(new Callback<Bean>() { @Override public void onResponse(Call<Bean> call, Response<Bean> response) { if (!response.isSuccessful()) { tv.setText("請求失敗,錯誤碼:" + response.code()); return; } Bean bean = response.body(); tv.setText(bean.toString()); } @Override public void onFailure(Call<Bean> call, Throwable t) { tv.setText(t.getMessage()); } });