使用GET与POST方式获取html数据
2015-09-02 17:17
639 查看
最近在弄着抓去网站数据解析的工作,其中,使用到GET和POST方法获取html数据。
使用GET方式:
使用POST方式:
其中,参数params的封装可以参照以下方式:
使用GET方式:
/** * 使用get方式获取html数据 * * @param strURL(需要访问的网站) * @return * @throws Exception */ public String getHTML(String strURL) throws Exception { //创建浏览器 HttpClient httpClient = HttpClients.createDefault(); String html = null; //预防网址链接中包含特殊字符,将url转为uri URL url = new URL(strURL); URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); //使用get方式 HttpGet request = new HttpGet(uri); HttpResponse response; try { //连接网址获取返回的数据 response = httpClient.execute(request); //将返回的数据按照gbk的方式编码 html = EntityUtils.toString(response.getEntity(), "GBK"); } catch (IOException e) { e.printStackTrace(); } //断开连接 request.abort(); //返回网址所发挥的html数据 return html; }使用该方法便可以获取得到网站所发挥的html数据。
使用POST方式:
/** * 使用post方式获取html数据 * * @param libraryUrl(需要访问的网站) * @param params(需要传入的参数) * @return * @throws Exception */ public String postHTML(String strURL, List<NameValuePair> params) throws Exception { //创建浏览器 HttpClient httpClient = HttpClients.createDefault(); String html = null; //预防网址链接中包含特殊字符,将url转为uri URL url = new URL(strURL); URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); //使用POST方式 HttpPost request = new HttpPost(uri); //将参数封装进UrlEncodedFormEntity中 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); request.setEntity(entity); HttpResponse response; try { //连接网址获取返回的数据 response = httpClient.execute(request); //将返回的数据按照gbk的方式编码 html = EntityUtils.toString(response.getEntity(), "GBK"); } catch (IOException e) { e.printStackTrace(); } //断开连接 request.abort(); //返回网址所发挥的html数据 return html; }
其中,参数params的封装可以参照以下方式:
List<NameValuePair> params = new ArrayList<NameValuePair>(); //以键值对的方式存储 params.add(new BasicNameValuePair("format", "hitcount"));
相关文章推荐
- 将html导出到excel或word
- HTML中id,name,class的区别
- html经验
- uploadify 上传插件的使用(视频和图片都可以上传)
- [freemarker篇]02.生成HTML的静态页面
- HTML <!DOCTYPE>
- jacob将Office文件转换为html文件工具类
- html 简介和基本格式
- HTML 5 Canvas
- visual studio粘贴html代码.会自行添加一些未知代码(自动格式化)
- IE6/IE7/IE8/IE9中tbody的innerHTML不能赋值的完美解决方案
- HTML头部
- html 杂
- html,列表<ol>,<ul>,<dl>
- html表单中get与post之间的区别
- html的表单
- html 的table
- HTML URL 编码
- 省市县联查 三级联动
- 网页一键分享按钮HTML代码