设为首页 加入收藏

TOP

如何使用Google Volley网络库发起带Header的HTTP请求?
2014-11-23 21:26:33 来源: 作者: 【 】 浏览:17
Tags:如何 使用 Google Volley 网络 发起 Header HTTP 请求

By Long Luo


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


JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener() {
@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 getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
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.


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇使用 Chrome 开发工具的设备模式.. 下一篇Android UI Layout总结之5大布局

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: