Пример #1
0
 public static void main(String[] args) {
   HttpClient client = new HttpClient(); // Create an instance of HttpClient.
   GetMethod method = new GetMethod(url); // Create a method instance.	
   method
       .getParams()
       .setParameter(
           HttpMethodParams.RETRY_HANDLER,
           new DefaultHttpMethodRetryHandler(
               3, false)); // Provide custom retry handler is necessary
   try {
     int statusCode = client.executeMethod(method); // Execute the method.
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + method.getStatusLine());
     }
     byte[] responseBody = method.getResponseBody(); // Read the response body.
     System.out.println(
         new String(
             responseBody)); // Deal with the response.// Use caution: ensure correct character
                             // encoding and is not binary data
   } catch (HttpException e) {
     System.err.println("Fatal protocol violation: " + e.getMessage());
     e.printStackTrace();
   } catch (IOException e) {
     System.err.println("Fatal transport error: " + e.getMessage());
     e.printStackTrace();
   } finally {
     method.releaseConnection(); // Release the connection.
   }
 }
Пример #2
0
 // ���� URL ָ�����ҳ
 public String downloadFile(String url) {
   String filePath = null;
   // 1.���� HttpClinet��������
   HttpClient httpClient = new HttpClient();
   // ���� HTTP���ӳ�ʱ 5s
   httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
   // 2.���� GetMethod��������
   GetMethod getMethod = new GetMethod(url);
   // ���� get����ʱ 5s
   getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
   // �����������Դ���
   getMethod
       .getParams()
       .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
   // 3.ִ��GET����
   try {
     int statusCode = httpClient.executeMethod(getMethod);
     // �жϷ��ʵ�״̬��
     if (statusCode != HttpStatus.SC_OK) {
       System.err.println("Method failed: " + getMethod.getStatusLine());
       filePath = null;
     }
     // 4.���� HTTP ��Ӧ����
     byte[] responseBody = getMethod.getResponseBody(); // ��ȡΪ�ֽ�����
     // ������ҳ url ���ɱ���ʱ���ļ���
     filePath =
         "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
     File file = new File(filePath);
     if (!file.getParentFile().exists()) {
       file.getParentFile().mkdir();
     }
     saveToLocal(responseBody, filePath);
   } catch (HttpException e) {
     // �����������쳣��������Э�鲻�Ի��߷��ص�����������
     System.out.println("�������http��ַ�Ƿ���ȷ");
     e.printStackTrace();
   } catch (IOException e) {
     // ���������쳣
     e.printStackTrace();
   } finally {
     // �ͷ�����
     getMethod.releaseConnection();
   }
   return filePath;
 }