View Javadoc

1   package org.helyx.basics4me.lang;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   
6   import javax.microedition.io.Connector;
7   import javax.microedition.io.HttpConnection;
8   
9   public class UrlUtil {
10  	
11  	private static final String HTTP_SCHEME = "http://";
12  	private static final String HTTPS_SCHEME = "https://";
13  	
14  	private static final String HTTP_HEADER_FIELD_USER_AGENT = "User-Agent";
15  	private static final String HTTP_HEADER_FIELD_LOCATION = "Location";
16  
17  	private static final String DEFAULT_USER_AGENT = "Profile/MIDP-2.0 Configuration/CLDC-1.1";
18  
19  	private UrlUtil() {
20  		super();
21  	}
22  	
23  	public static InputStream openStream(String url) throws IOException {
24  		return openStream(url, DEFAULT_USER_AGENT);
25  	}
26  	
27  	public static InputStream openStream(String url, String userAgent) throws IOException {
28  		String urlToLowerCase = url.toLowerCase();
29  		if (urlToLowerCase.startsWith(HTTP_SCHEME) || urlToLowerCase.startsWith(HTTPS_SCHEME)) {
30  			HttpConnection httpConnection = (HttpConnection)Connector.open(url);
31  	        httpConnection.setRequestMethod(HttpConnection.GET);
32  	        httpConnection.setRequestProperty(HTTP_HEADER_FIELD_USER_AGENT, userAgent);
33  	        
34  	        int httpResponseCode = httpConnection.getResponseCode();
35  	        int redirectCount = 0;
36  			if ( httpResponseCode == HttpConnection.HTTP_MOVED_PERM ||
37  					httpResponseCode == HttpConnection.HTTP_MOVED_TEMP ||
38  					httpResponseCode == HttpConnection.HTTP_SEE_OTHER ) {
39  				redirectCount++;
40  				if (redirectCount > 3) {
41  					String urlRedirection = httpConnection.getHeaderField(HTTP_HEADER_FIELD_LOCATION);
42  					httpConnection.close();
43  					throw new IOException("3rd try - Http Response Code: '" + httpResponseCode + "', Actual URL redirection: '" + urlRedirection + "'");
44  				}
45  				String urlRedirection = httpConnection.getHeaderField(HTTP_HEADER_FIELD_LOCATION);
46  				httpConnection.close();
47  				httpConnection = (HttpConnection)Connector.open(urlRedirection);
48  		        httpConnection.setRequestMethod(HttpConnection.GET);
49  		        httpConnection.setRequestProperty(HTTP_HEADER_FIELD_USER_AGENT, userAgent); 
50  		        httpResponseCode = httpConnection.getResponseCode();
51  			}	
52  			
53  			httpResponseCode = httpConnection.getResponseCode();
54  			if (httpResponseCode != HttpConnection.HTTP_OK) {
55  				String httpResponseMessage = httpConnection.getResponseMessage();
56  				String errorMessage = httpResponseCode + " - "+ httpResponseMessage;
57  			    throw new IOException(errorMessage);	 
58  			}		
59  
60  			InputStream inputStream = httpConnection.openInputStream();
61  			return inputStream;
62  		}
63  		
64  		InputStream inputStream = UrlUtil.class.getResourceAsStream(url);
65  		return inputStream;
66  	}
67  	
68  }