1.概述
在本教程中,我们将查看如何使用HttpClient设置自定义标题。
如果你想深入挖掘了解你可以用httpclient做的其他很酷的事情- 前往主httpclient教程。
进一步阅读:
2.设置标题,请求 - 4.3及以上
httpclient 4.3推出了一种建立的新方法 - 该RequestBuilder.。设置标题,我们将使用它s方法 - 在构建器上:
httpclient client = httpclient.custom()。build();httpurirequest请求= requestbuilder.get().seturi(sample_url).setheader(httpheaders.content_type,“application / json”).build();client.execute(请求);
3.在请求中设置标题 - 在4.3之前
在httpclient的第4.3版中,我们可以用简单的请求设置任何自定义标题s请求请求:
httpclient client = new defaultttpclient();httpget请求= new httpget(sample_url);Request.setheader(httpheaders.content_type,“application / json”);client.execute(请求);
我们可以看到,我们正在设置内容类型直接对自定义价值的请求 - JSON。
4.在客户端上设置默认标头
我们也可以通过每个请求设置标题将其配置为客户端上的默认标题本身:
标题标题=新展示者(httpheaders.content_type,“application / json”);列表<标题>标题= lists.newarraylist(标题);httpclient client = httpclient.custom()。setDefaultheaders(标题).build();httpurirequest请求= requestbuilder.get()。seturi(sample_url).build();client.execute(请求);
当标题对所有请求都需要相同的情况 - 例如自定义应用程序标题时,这是非常有帮助的。
结论
本文说明了如何将HTTP标头添加到通过Apache HttpClient发送的一个或所有请求。
可以找到所有这些示例和代码片段的实现GitHub项目。