HttpClient设置请求及处理响应
设置请求头:
package com.dahai.httpclientTest; import org.apache.http.Header; import org.apache.http.client.methods.HttpPost; public class HttpClientRequestHeaderTest { public static void main(String[] args) { // TODO Auto-generated method stub HttpPost httppost = new HttpPost(""); httppost.addHeader("Cookie", "key1=value1;key2=value2"); httppost.addHeader("User-Agent","My user Agent"); for(Header h:httppost.getAllHeaders()){ System.out.println(h); } } }
控制台输出:
Cookie: key1=value1;key2=value2
User-Agent: My user Agent
HTTP请求可以通过addHeader()方法设置请求头,通过getAllHeaders()方法获取所有请求头信息(用一个请求头数组表示)
一般POST请求需要设置的请求头包括:
method:POST
scheme:http,https
accept:代表客户端希望接受的数据类型,一般包括:application/json, text/xml, */*等
Content-Type:代表发送端发送的实体数据的数据类型,一般包括:application/json, text/xml, */*等
cookie:指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据
user-agent:访问者使用的工具
响应处理:
package com.dahai.httpclientTest; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientResponseTest { public static void main(String[] args) { // TODO Auto-generated method stub CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost:8080/mobilePhone?model=iPhone+6S"); CloseableHttpResponse response = null; try { response = client.execute(httpget); // System.out.println(response.getProtocolVersion()); System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getStatusLine().toString()); System.out.println(response.getEntity().getContentType()); //关闭服务器响应 response.close(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
控制台输出:
HTTP/1.1
200
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
response.getProtocolVersion():获取响应的协议版本
response.getStatusLine().getStatusCode():获取响应的响应行及响应码
response.getStatusLine().toString():获取响应的响应行并将整个响应行转换成字符串
response.getEntity().getContentType():获取响应实体并通过实体得到Content-Type
response.getAllHeaders():获取响应头内容(用一个请求头数组表示),可通过for(Header h:response.getAllHeaders()){System.out.println(h)}打印出来