Code example for HttpsURLConnection

Methods: disconnectgetResponseCodesetRequestMethodconnectsetDoInputsetRequestProperty

0
	private HttpsURLConnection getConnection(String address, String method)
			throws IOException { 
		System.out.println("getConnection: " + address);
		HttpsURLConnection con = (HttpsURLConnection) new URL(address)
				.openConnection();
		con.setRequestMethod(method);
		con.setRequestProperty("User-Agent", "CloudRAID");
		con.setRequestProperty("Accept", "*/*");
		if (this.accessToken != null) {
			con.setRequestProperty("Authorization", this.accessToken);
		} 
		return con;
	} 
 
	/** 
	 * Checks, if a file is in the specific folder on the SugarSync servers. 
	 *  
	 * @param name 
	 *            The file name. 
	 * @param parent 
	 *            The URL to the parent folder. 
	 * @return The URL to the file, or null, if it could not be found. 
	 * @throws SAXException 
	 *             Thrown, if the content cannot be parsed 
	 * @throws IOException 
	 *             Thrown, if no data can be written 
	 * @throws ParserConfigurationException 
	 *             Thrown, if the content cannot be parsed 
	 */ 
	private String getFileURL(String name) throws SAXException, IOException,
			ParserConfigurationException { 
		String url = this.urlCache.get(name);
		if (url != null) {
			return url;
		} 
		Document doc = null;
		String parent = this.getBaseUrl() + "/contents?type=file";
		HttpsURLConnection con = this.getConnection(parent, "GET");
		con.setDoInput(true);
 
		// Build the XML tree. 
		con.connect();
		try { 
			doc = this.docBuilder.parse(con.getInputStream());
			con.getInputStream().close();
		} finally { 
			con.disconnect();
		} 
		NodeList nl = doc.getDocumentElement().getElementsByTagName("file");
		for (int i = 0; i < nl.getLength(); i++) {
			String displayName = ((Element) nl.item(i))
					.getElementsByTagName("displayName").item(0)
					.getTextContent();
			if (displayName.equalsIgnoreCase(name)) {
				url = ((Element) nl.item(i)).getElementsByTagName("ref")
						.item(0).getTextContent();
				this.urlCache.put(name, url);
				return url;
			} 
		} 
		return null; 
	} 
 
	@Override 
	public byte[] getMetadata(String resource, int size) {
		InputStream is = performGet(resource, "m");
		if (is == null) {
			return null; 
		} 
		BufferedInputStream bis = new BufferedInputStream(is);
		byte meta[] = new byte[size];
		Arrays.fill(meta, (byte) 0);
		try { 
			bis.read(meta, 0, size);
		} catch (IOException ignore) {
			meta = null;
		} finally { 
			try { 
				bis.close();
			} catch (Exception ignore) {
			} 
		} 
		return meta;
	} 
 
	/** 
	 * Gets a refresh token from the SugarSync servers. 
	 *  
	 * @param username 
	 *            The user name of a SugarSync user. 
	 * @param password 
	 *            The regarding password. 
	 * @param appKey 
	 *            The app key of this app. 
	 * @return The refresh token, or null on error. 
	 */ 
	private String getRefreshToken(String username, String password,
			String appKey) {
		try { 
			// Get the Access Token 
			HttpsURLConnection con = this.getConnection(
					SugarSyncConnector.APP_AUTH_URL, "POST");
			con.setDoOutput(true);
			con.setRequestProperty("Content-Type",
					"application/xml; charset=UTF-8"); 
 
			// Create authentication request 
			String authReq = String.format(SugarSyncConnector.AUTH_REQUEST,
					new Object[] { username, password, appKey,
							this.accessKeyId, this.privateAccessKey });
 
			con.connect();
			try { 
				con.getOutputStream().write(authReq.getBytes());
				return con.getHeaderField("Location");
			} finally { 
				con.disconnect();
			} 
		} catch (Exception e) {
			return null; 
		} 
	} 
 
	/** 
	 * Executes the actual deletion of a file. 
	 *  
	 * @param resource 
	 *            The resource name. 
	 * @param extension 
	 *            The extension of the file. 
	 * @return true, if the deletion was successful; false, if not. 
	 */ 
	private boolean performDelete(String resource, String extension) {
		resource += "." + extension;
		// Find URL of resource in parent directory 
		try { 
			String resourceURL = this.getFileURL(resource);
			if (!this.performDeleteResource(resource, resourceURL)) {
				return false; 
			} 
		} catch (Exception e) {
			e.printStackTrace();
			return true; 
		} 
		return true; 
	} 
 
	/** 
	 * Actually deletes a resource on the given URL. 
	 *  
	 * @param name 
	 *            The name of the resource. 
	 * @param resourceURL 
	 *            The URL of the resource. 
	 */ 
	private boolean performDeleteResource(String name, String resourceURL) {
		HttpsURLConnection con = null;
		try { 
			con = this.getConnection(resourceURL, "DELETE");
			con.setDoInput(true);
			con.connect();
			int respCode = con.getResponseCode();
			if (!(respCode == 404 || (respCode >= 200 && respCode <= 299))) {
				return false; 
			} 
		} catch (Exception e) {
			e.printStackTrace();
		} finally { 
			if (con != null) {
				con.disconnect();
			} 
		} 
		this.urlCache.remove(name);
		return true; 
	}