java httpclient教程_HttpClient4.5.2 HTTP协议的请求和执行

本文详细介绍了如何使用HttpClient发起HTTP请求,并展示了如何处理响应。包括GET请求的实现方式、构造请求URI的方法以及解析HTTP响应的各项细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个HTTP方法的执行可以包含一个或多个HTTP请求/HTTP响应交换,通常由HttpClient的内部来处理。而期望用户提供一个要执行的请求对象,而HttpClient期望传输请求到目标服务器并返回对应的响应对象,或者当执行不成功时抛出异常。

案例代码:import java.io.InputStream;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientDemo {

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

// 1、创建HttpClient客户端类

HttpClient httpclient = new DefaultHttpClient();

// 2、创建GET请求类

HttpGet httpget = new HttpGet("http://www.baidu.com/");

// 3、执行GET请求

HttpResponse response = httpclient.execute(httpget);

// 4、获取执行返回结果

HttpEntity entity = response.getEntity();

// 5、打印执行结果输出内容

if (entity != null) {

InputStream instream = entity.getContent();

int l;

byte[] bytes = new byte[2048];

while ((l = instream.read(bytes)) != -1) {

String html = new String(bytes,0,l,"utf-8");

System.out.println(html);

}

}

}

}

所有HTTP请求有一个组合了的方法名,请求URI和HTTP协议版本的请求行。

HttpClient支持所有定义在HTTP/1.1版本中的HTTP方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS。对于每个方法类型都有一个特殊的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions。

请求URI的使用:

请求的URI是统一资源定位符,它标识了应用于哪个请求之上的资源。HTTP请求URI包含一个协议模式,主机名称,可选的端口,资源路径,可选的查询和可选的片段。

完成拼接URL:String url = "http://www.baidu.com/s" +

"?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu";

HttpGet httpget = new HttpGet(url);

System.out.println(httpget.getURI());

URIUtils类来拼装:URI uri = URIUtils.createURI("http", "www.baidu.com", -1, "/s",

"ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu", null);

HttpGet httpget = new HttpGet(uri);

System.out.println(httpget.getURI());

NameValuePair生成:List qparams = new ArrayList();

qparams.add(new BasicNameValuePair("ie", "utf-8"));

qparams.add(new BasicNameValuePair("f", "8"));

qparams.add(new BasicNameValuePair("rsv_bp", "0"));

qparams.add(new BasicNameValuePair("rsv_idx", "1"));

qparams.add(new BasicNameValuePair("tn", "baidu"));

URI uri = URIUtils.createURI("http", "www.baidu.com", -1, "/s",

URLEncodedUtils.format(qparams, "UTF-8"), null);

HttpGet httpget = new HttpGet(uri);

System.out.println(httpget.getURI());

输出:

http://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu

HTTP响应:// HTTP1.1响应

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,

HttpStatus.SC_OK, "OK");

// 版本号

System.out.println(response.getProtocolVersion());

// 状态码

System.out.println(response.getStatusLine().getStatusCode());

System.out.println(response.getStatusLine().getReasonPhrase());

System.out.println(response.getStatusLine().toString());

HTTP响应是由服务器在接收和解释请求报文之后返回发送给客户端的报文。响应报文的第一行包含了协议版本,之后是数字状态码和相关联的文本段。

HTTP协议头:

一个HTTP报文可以包含很多描述如内容长度,内容类型等信息属性的头部信息。HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,

HttpStatus.SC_OK, "OK");

response.addHeader("Set-Cookie","c1=a; path=/; domain=localhost");

response.addHeader("Set-Cookie","c2=b; path=\"/\", c3=c; domain=\"localhost\"");

Header h1 = response.getFirstHeader("Set-Cookie");

System.out.println(h1);

Header h2 = response.getLastHeader("Set-Cookie");

System.out.println(h2);

Header[] hs = response.getHeaders("Set-Cookie");

System.out.println(hs.length);

获得给定类型的所有头部信息最有效的方式是使用HeaderIterator接口。HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,

HttpStatus.SC_OK, "OK");

response.addHeader("Set-Cookie",

"c1=a; path=/; domain=localhost");

response.addHeader("Set-Cookie",

"c2=b; path=\"/\", c3=c; domain=\"localhost\"");

HeaderIterator it = response.headerIterator("Set-Cookie");

while (it.hasNext()) {

System.out.println(it.next());

}

解析HTTP报文到独立头部信息元素的方法方法。// HttpResponse对象

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,

HttpStatus.SC_OK, "OK");

response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");

response.addHeader("Set-Cookie",

"c2=b; path=\"/\", c3=c; domain=\"localhost\"");

// 遍历

HeaderElementIterator it = new BasicHeaderElementIterator(response

.headerIterator("Set-Cookie"));

while (it.hasNext()) {

HeaderElement elem = it.nextElement();

System.out.println(elem.getName() + " = " + elem.getValue());

NameValuePair[] params = elem.getParameters();

for (int i = 0; i 

System.out.println(" " + params[i]);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值