最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android的OkHttp包處理用戶認(rèn)證的代碼實(shí)例分享

 更新時間:2016年07月13日 16:00:48   作者:成富  
OkHttp包(GitHub主頁github.com/square/okhttp)是一款高人氣安卓HTTP支持包,這里我們來看一下Android的OkHttp包處理用戶認(rèn)證的代碼實(shí)例分享:

OkHttp 提供了對用戶認(rèn)證的支持。當(dāng) HTTP 響應(yīng)的狀態(tài)代碼是 401 時,OkHttp 會從設(shè)置的 Authenticator 對象中獲取到新的 Request 對象并再次嘗試發(fā)出請求。Authenticator 接口中的 authenticate 方法用來提供進(jìn)行認(rèn)證的 Request 對象,authenticateProxy 方法用來提供對代理服務(wù)器進(jìn)行認(rèn)證的 Request 對象。
用戶認(rèn)證的示例:

OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new Authenticator() {
public Request authenticate(Proxy proxy, Response response) throws IOException {
  String credential = Credentials.basic("user", "password");
  return response.request().newBuilder()
      .header("Authorization", credential)
      .build();
}

public Request authenticateProxy(Proxy proxy, Response response) 
throws IOException {
  return null;
}
});

進(jìn)階
當(dāng)需要實(shí)現(xiàn)一個 Basic challenge, 使用 Credentials.basic(username, password) 來編碼請求頭。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
 client.setAuthenticator(new Authenticator() {
  @Override public Request authenticate(Proxy proxy, Response response) {
   System.out.println("Authenticating for response: " + response);
   System.out.println("Challenges: " + response.challenges());
   String credential = Credentials.basic("jesse", "password1");
   return response.request().newBuilder()
     .header("Authorization", credential)
     .build();
  }

  @Override public Request authenticateProxy(Proxy proxy, Response response) {
   return null; // Null indicates no attempt to authenticate.
  }
 });

 Request request = new Request.Builder()
   .url("http://publicobject.com/secrets/hellosecret.txt")
   .build();

 Response response = client.newCall(request).execute();
 if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

 System.out.println(response.body().string());
}

相關(guān)文章

最新評論

娱乐| 胶州市| 佛山市| 碌曲县| 伊川县| 兴宁市| 肃南| 大余县| 荥经县| 淳安县| 南京市| 仁化县| 九江市| 宝清县| 绥滨县| 娱乐| 嘉义市| 简阳市| 铅山县| 新化县| 长宁区| 灵丘县| 西吉县| 郁南县| 宿迁市| 玛沁县| 绿春县| 阜宁县| 前郭尔| 易门县| 驻马店市| 准格尔旗| 海晏县| 菏泽市| 卓尼县| 全椒县| 栾城县| 邛崃市| 湖州市| 元阳县| 神池县|