Code example for HttpURLConnection

Methods: connect, disconnect, getContentEncoding, getContentType, getErrorStream, getHeaderFields, getInputStream, getResponseCode, setDoInput, setDoOutput

0
 
	static public ConnectionStreamResult getStreamResource(CouchContext ctxt, URL url) throws Exception {
		CouchContextBase context = CouchContextBase.getBase(ctxt);
		 
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		context.adjustConnection(conn);
		conn.setDoInput(true);
		conn.setDoOutput(false);
		conn.connect();
		updateContextFromHeaderFields(ctxt,conn.getHeaderFields());
		try { 
			checkResponseForError(conn);
		} catch(Exception e) {
			try { 
				conn.disconnect();
			} catch(Exception e2) {
				// Ignore 
			} 
			throw e;
		} 
		String contentType = conn.getContentType();
		String contentEncoding = conn.getContentEncoding();
		InputStream contentStream = conn.getInputStream();
		 
		ConnectionStreamResult result = new ConnectionStreamResult();
		result.setContentType(contentType);
		result.setContentEncoding(contentEncoding);
		result.setInputStream(contentStream);
 
		return result;
	} 
	 
	/** 
	 * Analyze a CouchDb response and raises an exception if an error was returned 
	 * in the response. 
	 * @param response JSON response sent by server 
	 * @param errorMessage Message of top exception 
	 * @throws Exception If error is returned in response 
	 */ 
	static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
		if( null == response ) {
			throw new Exception("Capturing errors from null response");
		} 
		if( false == (response instanceof JSONObject) ) {
			// Not an error 
			return; 
		} 
		JSONObject obj = (JSONObject)response;
		if( JSONSupport.containsKey(obj,"error") ) {
			String serverMessage;
			try { 
				serverMessage = obj.getString("error");
			} catch (Exception e) {
				serverMessage = "Unable to parse error response";
			} 
			 
			if( null == errorMessage ) {
				errorMessage = "Error returned by database: ";
			} 
			throw new Exception(errorMessage+serverMessage);
		} 
	} 
	 
	static public void updateContextFromHeaderFields(CouchContext context, Map<String,List<String>> headerFields){
		// Cookies 
		if( headerFields.containsKey("Set-Cookie") 
		 && context instanceof AcceptsCookies ) {
			AcceptsCookies acceptsCookies = (AcceptsCookies)context;
			List<String> cookies = headerFields.get("Set-Cookie");
			for(String cookie : cookies){
				String[] cookieComponents = cookie.split(";");
				if( cookieComponents.length > 0 ) {
					String[] cookieKeyValue = cookieComponents[0].split("=");
					if( cookieKeyValue.length >= 2 ) {
						acceptsCookies.setCookie(cookieKeyValue[0].trim(), cookieKeyValue[1].trim());
					}; 
				}; 
			} 
		} 
	} 
 
	static public void checkResponseForError(HttpURLConnection conn) throws Exception {
 
		int responseCode = conn.getResponseCode();
		if( responseCode < 200 || responseCode > 299 ) {
			// An error has been returned. Try to interpret the 
			// server response 
			String errorMsg = null;
			String reason = null;
			try { 
				String contentEncoding = conn.getContentEncoding();
				InputStream contentStream = conn.getErrorStream();
				if( null != contentStream ) {
					JSONObject result = getJsonFromInputStream(contentStream, contentEncoding, JSONObject.class);
					errorMsg = result.optString("error", "unknown");
					reason = result.optString("reason", "no reason given");
					contentStream.close();