/** * HTTPUtil.java * * This program is distributed under the terms of the GNU General Public * License * Copyright 2008 NJ Pearman * * This file is part of MobScrob. * * MobScrob is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MobScrob is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MobScrob. If not, see . */ package lastfm; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; /** * @author Neill * */ public class HTTPUtil { private static final String ENC_UTF8 = "UTF-8"; /** * Returns a Vector of Strings representing the lines present in the byte * array, separated by '\n' return feed. * * @param bytes * @return */ public static Vector readLines(byte[] bytes) { Vector lines = new Vector(); if (bytes == null || bytes.length == 0) { return lines; } StringBuffer line = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { if (bytes[i] == '\n') { lines.addElement(line.toString()); line = new StringBuffer(); } else { // add to current line line.append((char) bytes[i]); } } return lines; } /** * Encodes a parameter, also ensuring that it is UTF-8 * * @param s * @return * @throws UnsupportedEncodingException */ public static String encodeParam(String s) { if (s == null) return null; StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { default: if (ch < '\200') { sb.append(ch); break; } if (ch > '\177' && ch < '\u0800') { sb.append('%'); sb.append(Integer.toHexString((ch >> 6 | 0xc0) + 256).substring(1)); sb.append('%'); sb.append(Integer.toHexString((ch & 0x3f | 0x80) + 256).substring(1)); break; } if (ch > '\u07FF' && ch < '\0') { sb.append('%'); sb.append(Integer.toHexString((ch >> 12 | 0xe0) + 256).substring(1)); sb.append('%'); sb.append(Integer.toHexString((ch >> 6 & 0x3f | 0x80) + 256).substring(1)); sb.append('%'); sb.append(Integer.toHexString((ch & 0x3f | 0x80) + 256).substring(1)); } break; case 0: //'\0' case 32: sb.append("%20"); break;// ' ' case 61: sb.append("%3d"); break;// '=' case 43: sb.append("%2b"); break;// '+' case 39: sb.append("%27"); break;// '\'' case 46: sb.append("%2E"); break;// '.' case 60: sb.append("%3c"); break;// '<' case 62: sb.append("%3e"); break;// '>' case 35: sb.append("%23"); break;// '#' case 37: sb.append("%25"); break;// '%' case 38: sb.append("%26"); break;// '&' case 123:sb.append("%7b"); break;// '{' case 125:sb.append("%7d"); break;// '}' case 92: sb.append("%5c"); break;// '\\' case 94: sb.append("%5e"); break;// '^' case 126:sb.append("%73"); break;// '~' case 91: sb.append("%5b"); break;// '[' case 93: sb.append("%5d"); break;// ']' case 58: sb.append("%3A"); break;// ':' case 47: sb.append("%2F"); break;// '/' case 63: sb.append("%3F"); break;// '?' case 45: sb.append("%2D"); break;// '-' case 33: sb.append("%21"); break;// '!' case 59: sb.append("%3B"); break;// ';' } } return sb.toString(); /*if (s == null) { return s; } // encode as UTF-8 String utf8Str; try { utf8Str = new String(s.getBytes(), ENC_UTF8); } catch (UnsupportedEncodingException ex) { utf8Str = s; } StringBuffer sb = new StringBuffer(utf8Str.length() * 3); char[] chars = utf8Str.toCharArray(); int next; // encode the chars in the UTF-8 String for (int i = 0; i < chars.length; i++) { next = chars[i]; if ((next >= 0x30 && next <= 0x39) || // 0-9 (next >= 0x41 && next <= 0x5A) || // A-Z (next >= 0x61 && next <= 0x7A)) { // a-z sb.append((char) next); } else if ((next == 0xA0)) { // ' ' (whitespace) sb.append('+'); } else { // encode all other chars sb.append("%"); if (next <= 0xf) { sb.append("0"); } sb.append(Integer.toHexString(next)); } } return sb.toString();*/ } /** * Attempts to open a URL using the GET method over HTTP and read the * response into a byte array. Any IOExceptions are simply thrown out of * this method to be caught elsewhere. * * @param url * @return * @throws IOException */ public static byte[] getUrl(String url, String headerHostname) throws IOException { HttpConnection conn = null; try { conn = (HttpConnection) Connector.open(url); // set the compulsory HTTP/1.1 Host: header, as GET conn.setRequestMethod(HttpConnection.GET); //if(!headerHostname.equals("")) conn.setRequestProperty("Host", headerHostname); byte[] body = readHttpResponse(conn); return body; } finally { closeHttpConnection(conn); } } /** * Reads the response from the specified HTTP connection into a byte array. * * @param conn * @return * @throws IOException */ public static byte[] readHttpResponse(HttpConnection conn) throws IOException { int rc = conn.getResponseCode(); if (rc != HttpConnection.HTTP_OK) { String msg = "HTTP response code not OK: " + rc; throw new IOException(msg); } // connect int len = (int) conn.getLength(); InputStream is = null; try { is = conn.openInputStream(); // read response if (len > -1) { byte[] body = new byte[len]; int actual = 0; int bytesread = 0; while ((bytesread != len) && (actual != -1)) { actual = is.read(body, bytesread, len - bytesread); bytesread += actual; } // do something return body; } else { // read byte by byte...? Vector bytes = new Vector(); Byte byteObj; int next; while ((next = is.read()) > -1) { byteObj = new Byte((byte) next); bytes.addElement(byteObj); } byte[] body = new byte[bytes.size()]; Enumeration e = bytes.elements(); int i = 0; while (e.hasMoreElements()) { byteObj = (Byte) e.nextElement(); body[i++] = byteObj.byteValue(); } return body; } } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } } } public static void closeHttpConnection(HttpConnection conn) { if (conn != null) { try { conn.close(); } catch (Exception e) {} } } }