歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 如何使用Google Volley網絡庫發起帶Header的HTTP請求?

如何使用Google Volley網絡庫發起帶Header的HTTP請求?

日期:2017/3/1 9:40:03   编辑:Linux編程

By Long Luo

由於合作的第三方iQiyi視頻的數據源更新速度很慢,通過和iQiyi反饋,於是提供了新的API接口。

通過閱讀新API接口說明,在發起HTTP Get請求時,必須**同時帶2個加密的Header參數**,分別是時間戳和MD5加密後的key、時間戳以及客戶端參數,否則無法返回正確的請求。

目前在Android客戶端使用的是Google開源Volley庫,支持各種HTTP請求,圖片緩存,JSON解析,性能十分強大。之前使用的接口都是直接發起HTTP Get請求,附帶相關參數即可。

通過閱讀Volley相關資料,找到了下列方法,可以在發起HTTP請求時,附帶Header參數,代碼如下所示:

public void makeHTTPrequest(String url) {
MyLog.d(TAG, "makeHTTPrequest, url=" + url);

JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
MyLog.d(TAG, "response=" + response);
parseiQiyiInterfaceImageResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
} else if (error instanceof ClientError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}

MyLog.e(TAG, "onErrorResponse, error=" + error);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("t", iQiyiInterface.getEncryptTimestamp());
headers.put("sign", iQiyiInterface.getSign());

// MyLog.d(TAG, "headers=" + headers);
return headers;
}
};

// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonObjRequest.setTag(TAG);
jsonObjRequest.setShouldCache(true);

mQueue.add(jsonObjRequest);
mQueue.start();
}

Header參數使用HashMap存儲。

獲取到JSON數據之後,剩下的就是解析數據了,在這裡就不贅述了。

在完成這個過程中,還遇到了很多小插曲,比如Header的sign值不支持大寫字母,結果前後也白費了不少力氣。apk燒寫到手機之後,還需要使用tcpdump抓取數據包,看是否返回了正確的數據。

最後發現了Chrome的一個Smart Header插件,完美的解決了以上問題,不需要每次抓包驗證返回結果了,直接在Chrome浏覽器即可,節省了大量時間。

總之,希望這篇文章對大家能有所幫助。謝謝!

Created by Long Luo at 2014-09-07 12:30:03 @Shenzhen, China.

Copyright © Linux教程網 All Rights Reserved