使用http客户端处理网络的基本步骤如下。
1、以get方式获取响应对象。
closeablehttpclienthttpclient=http clients.create default (;
http get http get=new http get (' http://www.Baidu.com/' );
closeablehttpresponseresponse=http client.execute (http get );
2、获取响应对象的实体。
htpentityentity=response.get entity (;
注: http客户机将Response主体和request post/put方法的主体封装在一个HttpEntity对象中。 有关正文的信息可以通过entity.getContenType (,entity.getContentLength ) )等方法获得。 但是,最重要的方法是在getContent () )中检索InputStream对象。
3、在Entity中获取InputStream对象,并处理回复内容。
is=entity.getContent (;
sc=newscanner(is;
//string filename=path.substring (path.lastindexof )‘/’)1);
String filename='2.txt ';
OS=newprintwriter(filename );
while(sc.Hasnext ) ) ) )。
OS.write(sc.nextline ) );
}
使用htpp客户端下载网页的完整代码如下:
package com.ljh.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Scanner;
importorg.Apache.http.http entity;
importorg.Apache.http.http status;
importorg.Apache.http.client.clientprotocolexception;
importorg.Apache.http.client.methods.closeablehttpresponse;
importorg.Apache.http.client.methods.http get;
importorg.Apache.http.impl.client.closeablehttpclient;
importorg.Apache.http.impl.client.http clients;
公共类下载web page {
publicstaticvoiddownloadpagebygetmethod () throws IOException { )。
//1,在HttpGet中获取响应对象
closeablehttpclienthttpclient=http clients.create default (;
http get http get=new http get (' http://www.Baidu.com/' );
closeablehttpresponseresponse=http client.execute (http get );
InputStream is=null;
Scanner sc=null;
Writer os=null;
response.get statusline (.get status code )==HttpStatus.SC_OK ) )。
try {
//2,获取响应的实体。
htpentityentity=response.get entity (;
//3,获取InputStream对象并处理内容
is=entity.getContent (;
sc=newscanner(is;
//string filename=path.substring (path.lastindexof )‘/’)1);
String filename='2.txt ';
OS=newprintwriter(filename );
while(sc.Hasnext ) ) ) )。
OS.write(sc.nextline ) );
}
} catch (clientprotocolexceptione ) )
e .打印任务跟踪(;
} finally {
if(sc!=null ) {
sc.close (;
}
if(is!=null ) {
is.close (;
}
if (操作系统!=null ) {
os.close (;
}
响应!=null ) {
response.close (;
}
}
}
}
publicstaticvoidmain (字符串[ ] args ) {
try {
downloadPagebyGetMethod (;
}catch(ioexceptione ) {
e .打印任务跟踪(;
}
}
}
注意:如果直接将HttpGet更改为HttpPost,返回的结果将错误,百度将返回302状态,即重定向,新浪将拒绝访问。 我们认为大多数网站不允许通过POST方法直接访问网站。
原文: 3358 blog.csdn.net/Fang Chao 3652/article/details/26247765