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;
 }
示例#3
0
  public static Data getHTTPData(
      HttpServletRequest req, HttpServletResponse res, String surl, long since)
      throws DataSourceException, IOException {

    int tries = 1;

    // timeout msecs of time we're allowed in this routine
    // we must return or throw an exception.  0 means infinite.
    int timeout = mTimeout;
    if (req != null) {
      String timeoutParm = req.getParameter("timeout");
      if (timeoutParm != null) {
        timeout = Integer.parseInt(timeoutParm);
      }
    }

    long t1 = System.currentTimeMillis();
    long elapsed = 0;
    if (surl == null) {
      surl = getURL(req);
    }

    while (true) {
      String m = null;

      long tout;
      if (timeout > 0) {
        tout = timeout - elapsed;
        if (tout <= 0) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes=p[0] + " timed out"
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-194", new Object[] {surl}));
        }
      } else {
        tout = 0;
      }

      try {
        HttpData data = getDataOnce(req, res, since, surl, 0, (int) tout);
        if (data.code >= 400) {
          data.release();
          throw new DataSourceException(errorMessage(data.code));
        }
        return data;
      } catch (HttpRecoverableException e) {
        // This type of exception should be retried.
        if (tries++ > mMaxRetries) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes="too many retries, exception: " + p[0]
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-217", new Object[] {e.getMessage()}));
        }
        mLogger.warn(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="retrying a recoverable exception: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-226", new Object[] {e.getMessage()}));
      } catch (HttpException e) {
        String msg =
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()});
        throw new IOException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()}));
      } catch (IOException e) {

        try {
          Class ssle = Class.forName("javax.net.ssl.SSLException");
          if (ssle.isAssignableFrom(e.getClass())) {
            throw new DataSourceException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="SSL exception: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-256", new Object[] {e.getMessage()}));
          }
        } catch (ClassNotFoundException cfne) {
        }

        throw e;
      }

      long t2 = System.currentTimeMillis();
      elapsed = (t2 - t1);
    }
  }