您的位置:首页 > 理论基础 > 计算机网络

Apache HttpComponents 简单说明

2013-10-20 14:02 120 查看
尽管java.net包通过HTTP访问资源提供了基本的功能,它没有提供充分的灵活性,许多应用程序所需的功能。 HttpClient的,旨在填补这一空白,通过提供一个高效,同比增长日期,且功能丰富的封装,实现客户端最新的HTTP标准和建议。

利用HttpClient的设计为可扩展,同时提供强大的支持基本的HTTP协议,可能是感兴趣的任何建筑物知道HTTP的客户端应用程序,如Web浏览器,Web服务客户端,或系统或扩展HTTP协议的分布式通信。

用Java的Socket编程,其中不乏一些苦味的代码。例如往OutputStream中写入HTTP协义GET方法的请求头。示例

Socket s=new Socket(host,80);
OutputStream os=s.getOutputStream();

PrintWriter osOut=new PrintWriter(os,true);
//add request param
osOut.println("GET "+path+"?"+param+" HTTP/1.1");
osOut.println("Host: "+host+"");
osOut.println("Accept-Language: en-us,en;q=0.5");
osOut.println("Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
osOut.println("Accept-Encoding: gzip,deflate");
osOut.println("Connection: Close");
osOut.println();


这种代码还是需要程序员多少了解一下HTTP协义,Apache HttpComponents项目通过提供一个高效,功能丰富的封装,实现客户端最新的HTTP标准和建议。下面是示例代码

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://news.csdn.net/rss_news.html");
try (CloseableHttpResponse response=httpclient.execute(httpGet)){
HttpEntity entity = response.getEntity();


从输入流中获取的代码与Socket并无二样,org.apache.http.HttpEntity有一个getContent方法返回java.io.InputStream,因为目标的响应内容所用的字符编码并不一定与当前jvm的字符集编码一致。

BufferedReader osIn=new BufferedReader(
new InputStreamReader(is,Charset.forName("UTF-8")));
//get response
StringBuilder sb=new StringBuilder();
String line=osIn.readLine();
while(line!=null){
sb.append(line);
line=osIn.readLine();
}


更多可以访问Apache HttpComponents tutorial

下面是一个简单的Socket GET方法代码

try {
//URL u=new URL("http://news.baidu.com/n?cmd=7&loc=4075&name=yantai&tn=rss");
URL u=new URL("http://news.csdn.net/rss_news.html");
String host=u.getHost();
String path=u.getPath();
String param=u.getQuery();

try {
Socket s=new Socket(host,80);
OutputStream os=s.getOutputStream();

PrintWriter osOut=new PrintWriter(os,true);
BufferedReader osIn=new BufferedReader(
new InputStreamReader(s.getInputStream(),Charset.forName("UTF-8")));

//add request param
osOut.println("GET "+path+"?"+param+" HTTP/1.1");
osOut.println("Host: "+host+"");
osOut.println("Accept-Language: en-us,en;q=0.5");
osOut.println("Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
osOut.println("Accept-Encoding: gzip,deflate");
osOut.println("Connection: Close");
osOut.println();

//get response
StringBuilder sb=new StringBuilder();
String line=osIn.readLine();
while(line!=null){
sb.append(line);
line=osIn.readLine();
}
s.close();
System.out.println(sb.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息