httpClient 의 get 방법

2065 단어 httpclient
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();
		}
	}

}	

좋은 웹페이지 즐겨찾기