package de.thedevstack.android.nextcloud.bookmark.share.rest; import android.util.Base64; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.net.ssl.HttpsURLConnection; /** */ public class NextcloudBookmarkRestClient { private static final String LOGTAG = "NCBookmarkRestClient"; private static final String BOOKMARK_APP_REST_API = "/apps/bookmarks/public/rest/v2/bookmark"; private final String username; private final String password; private final String serverUrl; private final String restApiBaseUrl; private HttpsURLConnection urlConnection; public NextcloudBookmarkRestClient(String serverUrl, String username, String password) { this.serverUrl = serverUrl; this.username = username; this.password = password; this.restApiBaseUrl = serverUrl + BOOKMARK_APP_REST_API; } private void openConnection(String url) throws IOException { this.urlConnection = (HttpsURLConnection) new URL(url).openConnection(); String encoded = Base64.encodeToString((this.username+":"+this.password).getBytes(StandardCharsets.UTF_8), 0); this.urlConnection.setRequestProperty("Authorization", "Basic "+encoded); } public boolean checkCredentials() { Log.d(LOGTAG, "checking credentials"); boolean validCredentials = false; try { this.openConnection(this.restApiBaseUrl); this.urlConnection.setRequestMethod("HEAD"); this.urlConnection.connect(); validCredentials = 401 != this.urlConnection.getResponseCode(); Log.d(LOGTAG, "credentials are " + validCredentials); } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (null != this.urlConnection) { this.urlConnection.disconnect(); } return validCredentials; } } public int addBookmark(String bookmarkUrl) { Log.d(LOGTAG, "trying to add bookmark for '" + bookmarkUrl + "'"); int responseCode = -1; StringBuffer sb = new StringBuffer(); InputStream is = null; try { this.openConnection(this.restApiBaseUrl + "?url=" + bookmarkUrl); this.urlConnection.setRequestMethod("POST"); this.urlConnection.connect(); is = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String inputLine = ""; while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } Log.d(LOGTAG, sb.toString()); responseCode = this.urlConnection.getResponseCode(); } catch (Exception e) { Log.e(LOGTAG, "Error while trying to add bookmark: " + e.getMessage()); } finally { Log.i(LOGTAG, "disconnecting..."); if (null != this.urlConnection) { this.urlConnection.disconnect(); } if (is != null) { try { is.close(); } catch (IOException e) { Log.d(LOGTAG, "Error closing InputStream"); } } return responseCode; } } }