public void execute() { client = new HttpClient(); // if (requestType.equals("GET")) { // Instantiate a GET HTTP method // HttpMethod method = new GetMethod(apiUrl); // if (!authentication.equals("")) { // method.setRequestHeader("Authorization", "basic " + authentication); // } try { int statusCode = client.executeMethod(method); System.out.println("QueryString>>> " + apiUrl); System.out.println("Status Text>>>" + HttpStatus.getStatusText(statusCode)); // Get data as a String System.out.println(method.getResponseBodyAsString()); // OR as a byte array byte[] res = method.getResponseBody(); // write to file FileOutputStream fos = new FileOutputStream("donepage.html"); fos.write(res); // release connection method.releaseConnection(); } catch (IOException e) { e.printStackTrace(); } // } }
// ���� 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; }