`
gcgmh
  • 浏览: 354323 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

httpClient的get方法

 
阅读更多
public class HttpClientTest {
	
	
	 public static void main(String[] args) {
		 HttpClient httpClient = new HttpClient();
		 GetMethod getMethod = new GetMethod("http://www.sina.com.cn");
		 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				    new DefaultHttpMethodRetryHandler());
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			System.out.println("charset-->" + getMethod.getResponseCharSet());
//			Header head =  getMethod.getResponseHeader("Content-Type");
//			System.out.println(head.getValue());
			Header[] headers=getMethod.getResponseHeaders();
				for (Header header : headers) {
					System.out.println(header.getName()+" "+header.getValue());

				}

			  if (statusCode != HttpStatus.SC_OK) {
				    System.err.println("Method failed: "
				      + getMethod.getStatusLine());
				   }
			  //适合小数据量的网站
//			  byte[] responseBody = getMethod.getResponseBody();
//			   System.out.println(new String(responseBody));
			  
			  
			  //适合大数据量网站
			  InputStream in = getMethod.getResponseBodyAsStream();
		       
		        byte[] responseBodyByte = null;

		        if (in!=null)
		        {
		         byte[] tmp = new byte[4096];
		         int bytesRead = 0;
		         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		         while((bytesRead = in.read(tmp))!=-1)
		         {
		          buffer.write(tmp,0,bytesRead);
		         }
		         responseBodyByte = buffer.toByteArray();
		        }
		       
		        System.out.println(new String(responseBodyByte));

		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			 getMethod.releaseConnection();
		}
	}

}	
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics