Code example for HttpURLConnection

Methods: getInputStream, setRequestMethod, setRequestProperty

0
	public static String useragent;
 
	/** mainly sets the User-Agent we need */ 
	private static void setUserAgent(HttpURLConnection conn) {
		if (useragent != null)
			conn.setRequestProperty("User-Agent", useragent);
	} 
 
	public static URL getRedirectedUrl(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		conn.setInstanceFollowRedirects(false);
		int rc = conn.getResponseCode();
		if (rc != REDIRECT_RESPONSE_CODE) {
			throw new IOException("code " + rc + " '" + conn.getResponseMessage() + "'");
		} 
		String location = conn.getHeaderField("Location");
		if (location == null) {
			throw new IOException("No 'Location' header found");
		} 
		return new URL(location);
	} 
 
	private static void copy(InputStream in, OutputStream out) throws IOException {
		byte[] buf = new byte[512];
		int bytesRead = 1;
		while (bytesRead > 0) {
			bytesRead = in.read(buf);
			if (bytesRead > 0) {
				out.write(buf, 0, bytesRead);
			} 
		} 
	} 
 
	private static int copy(InputStream in, OutputStream out, int maxBytes) throws IOException {
		byte[] buf = new byte[512];
		int bytesRead = 1;
		int totalBytes = 0;
		while (bytesRead > 0) {
			bytesRead = in.read(buf, 0, Math.min(512, maxBytes - totalBytes));
			if (bytesRead > 0) {
				out.write(buf, 0, bytesRead);
				totalBytes += bytesRead;
			} 
		} 
		return totalBytes;
	} 
 
	public static String doFormPost(URL url, String input) throws IOException {
		return doPost(url, new ByteArrayInputStream(input.getBytes()), "application/x-www-urlencoded");
	} 
 
	public static String doPost(URL url, String input) throws IOException {
		return doPost(url, new ByteArrayInputStream(input.getBytes()));
	} 
 
	public static String doPost(URL url, InputStream stuffToPost) throws IOException {
		return doPost(url, stuffToPost, null);
	} 
 
	public static String doPost(URL url, InputStream stuffToPost, String contentType) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		if (contentType != null) {
			conn.setRequestProperty("Content-Type", contentType);
		} 
		OutputStream ostr = null;
		try { 
			ostr = conn.getOutputStream();
			copy(stuffToPost, ostr);
		} finally { 
			if (ostr != null)
				ostr.close();
		} 
 
		conn.connect();
		BufferedReader reader = null;
		try { 
			int rc = conn.getResponseCode();
			InputStream contentStream = null;
			if (rc == 400)
				contentStream = conn.getErrorStream();
			else if (rc != 200) {
				throw new IOException("code " + rc + " '" + conn.getResponseMessage() + "'");
			} else 
				contentStream = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(contentStream), 512);
			String response = toString(reader);
			return response;
		} finally { 
			if (reader != null) {
				reader.close();
			} 
 
			// Dispatch any queued Analytics data while we've got the network 
			// open 
			GoogleAnalyticsTracker tracker = GoogleAnalyticsTracker.getInstance();
			tracker.dispatch();
		} 
	} 
 
	public static String doGet(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		BufferedReader reader = null;
		try { 
			int rc = conn.getResponseCode();
			if (rc != 200) {
				throw new IOException("code " + rc + " '" + conn.getResponseMessage() + "'");
			} 
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
			return toString(reader);
		} finally { 
			if (reader != null) {
				reader.close();
			} 
		} 
	} 
 
	/** 
	 * Do a GET request and retrieve up to maxBytes bytes 
	 *  
	 * @param url 
	 * @param maxBytes 
	 * @return 
	 * @throws IOException 
	 */ 
	public static byte[] doGetAndReturnBytes(URL url, int maxBytes) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		InputStream istr = null;
		try { 
			int rc = conn.getResponseCode();
			if (rc != 200) {
				throw new IOException("code " + rc + " '" + conn.getResponseMessage() + "'");
			} 
			istr = new BufferedInputStream(conn.getInputStream(), 512);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			copy(istr, baos, maxBytes);
			return baos.toByteArray();
		} finally { 
			if (istr != null) {
				istr.close();
			} 
		} 
	} 
 
	private static String buildUrl(String baseurl, Map<String, String> params) throws IOException {
		if (params.isEmpty()) {
			return baseurl;
		} else { 
			return baseurl + "?" + buildQuery(params);
		} 
	} 
 
	public static String buildQuery(Map<String, String> params) {
		StringBuilder sb = null;
		for (String key : params.keySet()) {
			String value = params.get(key);
			if (sb == null) {
				sb = new StringBuilder();
				sb.append(escape(key)).append('=').append(escape(value));
			} else { 
				sb.append("&").append(escape(key)).append('=').append(escape(value));
			} 
		} 
		return sb.toString();
 
	} 
 
	public static String doGet(String baseurl, Map<String, String> params) throws IOException {
		return doGet(new URL(buildUrl(baseurl, params)));
	} 
 
	public static String doPost(String baseurl, Map<String, String> params) throws IOException {
		return doPost(new URL(baseurl), buildQuery(params));
	} 
 
	private static String escape(String s) {
		try { 
			return URLEncoder.encode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			Log.e("UrlUtil", "Cannot find UTF-8 encoding - this is not very likely!");
			return s;
		} 
 
	} 
 
	public static String getXML(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		BufferedReader reader = null;
		try { 
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			return toString(reader);
		} finally { 
			if (reader != null) {
				reader.close();
			} 
		} 
	} 
 
	public static Bitmap getImage(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		return BitmapFactory.decodeStream(conn.getInputStream());
	} 
 
	private static String toString(BufferedReader reader) throws IOException {
		StringBuilder sb = new StringBuilder();
		String line;