设置DNS

This commit is contained in:
wujifei
2021-01-27 16:29:27 +08:00
parent facad1158f
commit a356490cb6
9 changed files with 147 additions and 86 deletions

View File

@@ -34,6 +34,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static com.mogo.cloud.commons.network.NetConstants.GEOFENCE_HOST;
import static com.mogo.cloud.commons.network.NetConstants.REALTIME_LOCATION_HOST;
/**
* created by wujifei on 2021/1/21 12:26
* describe:
@@ -51,18 +54,17 @@ public class NetworkActivity extends AppCompatActivity {
setContentView(R.layout.activity_network);
btn = (Button) findViewById(R.id.btn);
tvResult = (TextView) findViewById(R.id.tv_result);
apiService = RetrofitFactory.INSTANCE.getInstance("http://dzt-test.zhidaozhixing.com")
.create(ApiService.class);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvResult.setText("结果显示");
queryRoadData("ZD802C1938L10797");
// queryHelpSignal("ZD802C1938L10797");
// queryHelpSignal("F803EB2046PZD00006");
//上报路况到服务端
// uploadRoadInfo();
// uploadRoadInfo();
//查询路况
// queryRoad();
}
@@ -154,6 +156,8 @@ public class NetworkActivity extends AppCompatActivity {
}
public void queryRoadData(String sn) {
apiService = RetrofitFactory.INSTANCE.getInstance(GEOFENCE_HOST)
.create(ApiService.class);
if (apiService != null) {
Map<String, Object> map = new HashMap<>();
map.put("sn", sn);
@@ -187,6 +191,8 @@ public class NetworkActivity extends AppCompatActivity {
}
public void queryHelpSignal(String sn) {
apiService = RetrofitFactory.INSTANCE.getInstance("http://dzt-realtimeLocation.zhidaozhixing.com")
.create(ApiService.class);
if (apiService != null) {
Map<String, Object> map = new HashMap<>();
map.put("sn", sn);

View File

@@ -53,7 +53,6 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation rootProject.ext.dependencies.androidxccorektx
implementation rootProject.ext.dependencies.androidxappcompat
implementation rootProject.ext.dependencies.okhttpinterceptor
implementation rootProject.ext.dependencies.retrofit
implementation rootProject.ext.dependencies.retrofitadapter
implementation rootProject.ext.dependencies.retrofitconvertergson

View File

@@ -1,20 +0,0 @@
package com.mogo.cloud.commons.network
import android.text.TextUtils
import com.mogo.cloud.commons.utils.getInetAddressByHost
import okhttp3.Dns
import java.net.InetAddress
/**
* created by wujifei on 2021/1/26 12:51
* describe:
*/
class HttpDns : Dns {
override fun lookup(hostname: String): List<InetAddress> {
val addresses: List<InetAddress> = getInetAddressByHost(hostname)
if (!addresses.isEmpty()) {
return addresses
}
return Dns.SYSTEM.lookup(hostname)
}
}

View File

@@ -6,13 +6,26 @@ package com.mogo.cloud.commons.network
*/
class NetConstants {
companion object {
const val TAG = "LogInterceptor"
const val READ_TIMEOUT = 20000L
const val WRITE_TIMEOUT = 20000L
const val CONNECT_TIMEOUT = 15000L
const val HTTP_DNS_ADDRESS_TYPE_HTTP = 0
const val HTTP_DNS_ADDRESS_TYPE_WS = 1
const val HTTP_DNS_ADDRESS_TYPE_IM = 2
const val DEVA_HOST = "http://dzt-deva.zhidaozhixing.com"
const val IM_HOST = "http://dzt-im.zhidaozhixing.com"
const val LAUNCHER_SNAPSHOT_HOST = "http://dzt-launcherSnapshot.zhidaozhixing.com"
const val CHANNEL_MANAGER_HOST = "http://dzt-channelManager.zhidaozhixing.com"
const val DATA_SERVICE_HOST = "http://dzt-dataService.zhidaozhixing.com"
const val REALTIME_LOCATION_HOST = "http://dzt-realtimeLocation.zhidaozhixing.com"
const val INSTANT_HOST = "http://dzt-Instant.zhidaozhixing.com"
const val GEOFENCE_HOST = "http://dzt-geoFenceCarService.zhidaozhixing.com"
const val CARLIFE_HOST = "http://dzt-carlife.zhidaozhixing.com"
const val STRATEGY_PUSH_HOST = "http://dzt-strategyPush.zhidaozhixing.com"
const val TRAVEL_CONDITION_HOST = "http://dzt-travelCondition.zhidaozhixing.com"
const val TMC_HOST = "http://dzt-tmcServer.zhidaozhixing.com"
const val IM_SOCKET_DOMAIN = "dzt-im.zhidaozhixing.com"
const val WEBSOCKET_DOMAIN = "dzt-Instant.zhidaozhixing.com"
}
}

View File

@@ -5,12 +5,10 @@ import com.mogo.cloud.commons.network.NetConstants.Companion.READ_TIMEOUT
import com.mogo.cloud.commons.network.NetConstants.Companion.WRITE_TIMEOUT
import com.mogo.cloud.commons.network.SSLSocketFactoryUtils.createSSLSocketFactory
import com.mogo.cloud.commons.network.SSLSocketFactoryUtils.createTrustAllManager
import com.mogo.cloud.commons.network.interceptor.HeaderNetworkInterceptor
import com.mogo.cloud.commons.utils.lookup
import okhttp3.Dns
import com.mogo.cloud.commons.network.interceptor.HttpHeaderInterceptor
import com.mogo.cloud.commons.network.interceptor.HttpDnsInterceptor
import com.mogo.cloud.commons.network.interceptor.HttpLoggingInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.net.InetAddress
import java.util.concurrent.TimeUnit
@@ -22,16 +20,16 @@ import java.util.concurrent.TimeUnit
*/
class OkHttpFactory private constructor() {
companion object {
val okHttpClient: OkHttpClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
val okHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.addNetworkInterceptor(HeaderNetworkInterceptor())
.addNetworkInterceptor(HttpHeaderInterceptor())
.addInterceptor(HttpDnsInterceptor())
.addInterceptor(HttpLoggingInterceptor())
.sslSocketFactory(createSSLSocketFactory(), createTrustAllManager())
.hostnameVerifier(SSLSocketFactoryUtils.TrustAllHostnameVerifier())
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
.dns(HttpDns())
.build()
}

View File

@@ -0,0 +1,26 @@
package com.mogo.cloud.commons.network.interceptor
import com.mogo.cloud.httpdns.MogoHttpDnsClient
import com.mogo.utils.logger.Logger
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
/**
* created by wujifei on 2021/1/27 15:57
* describe:
*/
class HttpDnsInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val path: String = request.url().encodedPath()
val query: String? = request.url().encodedQuery()
val host = "http://" + MogoHttpDnsClient.getHttpDnsAddressUseCacheIfNecessary(0, request.url().host().replace("http://", "").replace("https://", ""))
var url = host + path
query?.let {
url=url+"?"+query
}
Logger.d("DomainExchange", """oriHost: ${request.url().host().toString()} newHost: $host newUrl: $url""")
return chain.proceed(request.newBuilder().url(url).build())
}
}

View File

@@ -8,7 +8,7 @@ import okhttp3.Response
* created by wujifei on 2021/1/20 15:18
* describe:header携带信息
*/
class HeaderNetworkInterceptor : Interceptor {
class HttpHeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val request = original.newBuilder()

View File

@@ -0,0 +1,87 @@
package com.mogo.cloud.commons.network.interceptor
import com.mogo.cloud.commons.network.NetConstants.Companion.TAG
import com.mogo.utils.logger.Logger
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
/**
* created by wujifei on 2021/1/27 14:33
* describe:
*/
class HttpLoggingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val requestBody = request.body()
val hasRequestBody = requestBody != null
var protocol = Protocol.HTTP_1_1.toString()
var body = ""
if (chain.connection() != null && chain.connection()!!.protocol() != null) {
protocol = chain.connection()!!.protocol().toString()
}
if (hasRequestBody) {
try {
val UTF8 = Charset.forName("UTF-8")
val buffer = Buffer()
requestBody?.writeTo(buffer)
var charset = UTF8
val contentType = requestBody?.contentType()
if (contentType != null) {
charset = contentType.charset(UTF8)
}
if (charset != null) {
body = buffer.readString(charset)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
val logMsg = StringBuilder()
.append("------> http request start").append("\r\n")
.append(protocol).append(", ")
.append(request.method()).append(", ")
.append("Request Headers: ").append(request.headers().toString()).append("\r\n")
.append("Url: ").append(request.url()).append("\r\n")
.append("Content-Type: ").append(requestBody?.contentType()).append("\r\n")
.append("Content-Length: ").append(requestBody?.contentLength()).append("\r\n")
.append("Content-body: ").append(body).append("\r\n")
.append("------> http request end").append("\r\n").append("\r\n")
val startTime = System.nanoTime()
val response = chain.proceed(chain.request())
val endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)
val responseBody = response.body()
var responseContent: String? = null
var bodySize: String? = null
var contentType: MediaType? = null
var consumedResponse = false
if (responseBody != null) {
val contentLength = responseBody.contentLength()
bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length"
contentType = responseBody.contentType()
responseContent = responseBody.string()
consumedResponse = true
}
logMsg.append("------> http response start").append("\r\n")
.append(response.code()).append(" ")
.append(response.message()).append(" ")
.append(response.protocol()).append(" ").append("\r\n")
.append("Response Content: ").append(responseContent).append("\r\n")
.append("Content-Type: ").append(contentType).append("\r\n")
.append("Content-Length: ").append(bodySize).append("\r\n")
.append(" (").append(endTime).append("ms)").append("\r\n")
.append("------> http response end")
Logger.d(TAG, logMsg.toString())
return if (consumedResponse) response.newBuilder().body(ResponseBody.create(contentType, responseContent)).build() else response
}
}

View File

@@ -1,48 +0,0 @@
package com.mogo.cloud.commons.utils
import android.text.TextUtils
import com.mogo.cloud.commons.network.NetConstants.Companion.HTTP_DNS_ADDRESS_TYPE_HTTP
import com.mogo.cloud.httpdns.MogoHttpDnsClient
import java.net.InetAddress
import java.net.UnknownHostException
import java.util.*
/**
* created by wujifei on 2021/1/20 12:51
* describe:网络工具
*/
/**
* 根据host获取InetAddress
*/
@Throws(UnknownHostException::class)
fun lookup(hostname: String?): List<InetAddress?>? {
val cacheIp: String? = hostname?.let { MogoHttpDnsClient.getHttpDnsAddressUseCacheIfNecessary(HTTP_DNS_ADDRESS_TYPE_HTTP, it) }
if (cacheIp == null || TextUtils.isEmpty(cacheIp)) {
return emptyList<InetAddress>()
}
val info = cacheIp.split(":").toTypedArray()
return if (info.size > 1) {
Arrays.asList(*InetAddress.getAllByName(info[0]))
} else {
Arrays.asList(*InetAddress.getAllByName(cacheIp))
}
}
/**
* 根据host获取InetAddress
*/
@Throws(UnknownHostException::class)
fun getInetAddressByHost(hostname: String): List<InetAddress> {
val cacheIp: String? = hostname?.let { MogoHttpDnsClient.getHttpDnsAddressUseCacheIfNecessary(HTTP_DNS_ADDRESS_TYPE_HTTP, it) }
if (cacheIp == null || TextUtils.isEmpty(cacheIp)) {
return emptyList<InetAddress>()
}
val info = cacheIp.split(":").toTypedArray()
return if (info.size > 1) {
Arrays.asList(*InetAddress.getAllByName(info[0]))
} else {
Arrays.asList(*InetAddress.getAllByName(cacheIp))
}
}