---
title: "httpclient抓取数据"
author: "leeny"
date: "2011-07-11T17:59:47Z"
tags: ["HTML", "Java"]
categories: ["编程语言"]
slug: "httpclient"
draft: false
lastmod: "2011-07-12T18:53:33Z"
id: 1121897
url: "https://leeny.iteye.com/blog/1121897"
---

今天下午闲来无事，就在iteye上泡着，看到了一篇关于用httpclient获取手机号归属地的一片博客。想到我正好需要一些职位名称，于是动手自己写了一个小程序来获取自己想要的数据。代码如下：

```java

  public static void main(String[] args) {
	  String url = "http://sou.zhaopin.com/jobtypelist.html";	  
	  getHttpClient(url);
 }

	private static void getHttpClient(String url) {
		//构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		  //创建GET方法的实例
		  GetMethod getMethod = new GetMethod(url);
		  //使用系统提供的默认的恢复策略
		  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		    new DefaultHttpMethodRetryHandler());
		  try {
			   //执行getMethod
			   int statusCode = httpClient.executeMethod(getMethod);
			   if (statusCode != HttpStatus.SC_OK) {
			    System.err.println("Method failed: "
			      + getMethod.getStatusLine());
			   }
			   //读取内容 
			   byte[] responseBody = getMethod.getResponseBody();
			   //处理内容
			   parseHTML(new String(responseBody));
		  } catch (HttpException e) {
			   //发生致命的异常，可能是协议不对或者返回的内容有问题
			   System.out.println("Please check your provided http address!");
			   e.printStackTrace();
		  } catch (IOException e) {
			   //发生网络异常
			   e.printStackTrace();
		  } finally {
			   //释放连接
			   getMethod.releaseConnection();
		  }
	}
  
	private static void saveFile(String txt){
		String filePath = "F:/category.txt";
		BufferedWriter out = null;
		 if(txt != null){
			 try {  
	             out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true),"UTF-8")); 
	             //一行一行的写入
	             out.write(txt + "\t\n");
	             out.flush();  
	         }catch(Exception e){
	        	 e.printStackTrace();
	         } finally {  
	             if (out != null)
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}  
	         }
		 }
	}

  private static void parseHTML(String content){
	 Document doc =  Jsoup.parse(content);
	 Elements categories = doc.select("li a");	 
	 for(int i=0; i<categories.size();i++){		 
		 String txt = categories.get(i).text();
		 saveFile(txt);
	}
  }

```

通过httpclient获得到页面的源代码之后，用Jsoup来解析html（这个是临时在网上查到的，不太会用），最后将数据保存到了文本中。
遇到的问题：
1.解析html，以前没有解析过，Jsoup也是临阵磨枪，得到了自己想要的结果还不错，下来再研究一下。
2.写入文件的时候，不能一行一行的写，没有想到用换行符，百度了一下。