工具类: compile ‘com.burgstaller:okhttp-digest:1.13’
import android.content.Context
import com.burgstaller.okhttp.AuthenticationCacheInterceptor
import com.burgstaller.okhttp.CachingAuthenticatorDecorator
import com.burgstaller.okhttp.DispatchingAuthenticator
import com.burgstaller.okhttp.digest.CachingAuthenticator
import com.burgstaller.okhttp.digest.Credentials
import com.burgstaller.okhttp.digest.DigestAuthenticator
import java.io.IOException
import java.util.Map
import java.util.concurrent.ConcurrentHashMap
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
public class HttpUtils {
private Context context
private CallBackResponse callback
static String resposes
public HttpUtils(Context context) {
this.context = context
}
public void setOnCallback(CallBackResponse callback) {
this.callback = callback
}
public interface CallBackResponse {
void onSuccess(String response)
}
public void pullNews(String url) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>()
Credentials credentials = new Credentials("Hsp-2E9D30C1C1914BC7A14E17E257648563",
"5894D3C2D891473E804A3814E5D61D4B")
final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials)
DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder().with("digest",
digestAuthenticator).build()
okhttp3.Request request = new okhttp3.Request.Builder().url(url).get()
.header("X-User-Id", "Hsp-2E9D30C1C1914BC7A14E17E257648563")
.header("X-Google-Ad-Id", "5894D3C2D891473E804A3814E5D61D4B").build()
OkHttpClient client = builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache))
.addInterceptor(new AuthenticationCacheInterceptor(authCache)).build()
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
resposes = response.body().string()
if (callback != null) {
callback.onSuccess(resposes)
}
}
})
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)