Here you can find the source of httpGet(String url, boolean logStdout)
Parameter | Description |
---|---|
url | A valid URL |
logStdout | if TRUE then this method will print a tracelog via STDOUT |
Parameter | Description |
---|---|
Throwable | an exception |
public static String httpGet(String url, boolean logStdout) throws Throwable
//package com.java2s; /**/* w w w.ja va 2 s . co m*/ * Core-level framework class: String and Date basic utility methods. * <br><br> * Encapsulates utility methods for everyday programming tasks * with Strings, Dates and other common stuff. * <br> * Creation date: 18/09/2003<br> * Last Update: 18/09/2003<br> * (c) 2003 Martin Cordova<br> * This code is released under the LGPL license<br> * @author Martin Cordova (some code written by Carlos Pineda) */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.*; public class Main { /** * Retrieve a text-based document using HTTP GET method.<br> * May be used to retrieve XML documents, news feeds, etc. * @param url A valid URL * @param logStdout if TRUE then this method will print * a tracelog via STDOUT * @return a String containing the whole document * @throws Throwable */ public static String httpGet(String url, boolean logStdout) throws Throwable { final int bufferSize = 4096; BufferedReader br = null; HttpURLConnection urlc = null; StringBuffer buffer = new StringBuffer(); URL page = new URL(url); try { if (logStdout) System.err.println("Waiting for reply...:" + url); urlc = (HttpURLConnection) page.openConnection(); urlc.setUseCaches(false); if (logStdout) { System.err.println("Content-type = " + urlc.getContentType()); System.err.println("Content-length = " + urlc.getContentLength()); System.err.println("Response-code = " + urlc.getResponseCode()); System.err.println("Response-message = " + urlc.getResponseMessage()); } int retCode = urlc.getResponseCode(); String retMsg = urlc.getResponseMessage(); if (retCode >= 400) throw new Throwable("HTTP Error: " + retCode + " - " + retMsg + " - URL:" + url); br = new BufferedReader(new InputStreamReader(urlc.getInputStream()), bufferSize); char buf[] = new char[bufferSize]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = br.read(buf); if (bytesRead > 0) buffer.append(buf, 0, bytesRead); } if (logStdout) { System.err.println("Document received."); } return buffer.toString(); } catch (Throwable e) { throw e; } finally { if (br != null) br.close(); if (urlc != null) urlc.disconnect(); } } }