Example usage for javax.net.ssl HttpsURLConnection setRequestMethod

List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setRequestMethod.

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

From source file:org.liberty.android.fantastischmemo.downloader.google.DocumentFactory.java

public static Document createSpreadsheet(String title, String authToken)
        throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from   w  w w.  j  av  a2  s . c  om
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.spreadsheet\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }

    return EntryFactory.getEntryFromDriveApi(Document.class, conn.getInputStream());
}

From source file:org.liberty.android.fantastischmemo.downloader.google.WorksheetFactory.java

public static void deleteWorksheet(Spreadsheet spreadsheet, Worksheet worksheet, String authToken)
        throws Exception {
    String requestUrl = "https://spreadsheets.google.com/feeds/worksheets/" + spreadsheet.getId()
            + "/private/full/" + worksheet.getId() + "/0" + "?access_token=" + authToken;
    URL url = new URL(requestUrl);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("DELETE");
    conn.addRequestProperty("If-Match", "*");
    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new Exception(s);
    }/*from  ww w  .  j  a  v a  2  s  .com*/
}

From source file:org.liberty.android.fantastischmemo.downloader.google.FolderFactory.java

public static void addDocumentToFolder(Document document, Folder folder, String authToken)
        throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files/" + document.getId() + "/parents");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);/* w  w  w.ja v  a 2s. com*/
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    String payload = "{\"id\":\"" + folder.getId() + "\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.google.FolderFactory.java

public static Folder createFolder(String title, String authToken) throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from  w  w w .j  a  v a2 s  .c  o  m
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    // Used to calculate the content length of the multi part
    String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.folder\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }

    return EntryFactory.getEntryFromDriveApi(Folder.class, conn.getInputStream());
}

From source file:org.liberty.android.fantastischmemo.downloader.google.WorksheetFactory.java

public static Worksheet createWorksheet(Spreadsheet spreadsheet, String title, int row, int col,
        String authToken) throws Exception {
    URL url = new URL("https://spreadsheets.google.com/feeds/worksheets/" + spreadsheet.getId()
            + "/private/full?access_token=" + authToken);

    String payload = "<entry xmlns=\"http://www.w3.org/2005/Atom\""
            + " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" + "<title>"
            + URLEncoder.encode(title, "UTF-8") + "</title>" + "<gs:rowCount>" + row + "</gs:rowCount>"
            + "<gs:colCount>" + col + "</gs:colCount>" + "</entry>";

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from w  ww.j  av a  2s .  com
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/atom+xml");
    conn.addRequestProperty("Content-Length", "" + payload.getBytes("UTF-8").length);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new Exception(s);
    }

    List<Worksheet> worksheets = getWorksheets(spreadsheet, authToken);
    for (Worksheet worksheet : worksheets) {
        if (title.equals(worksheet.getTitle())) {
            return worksheet;
        }
    }
    throw new IllegalStateException("Worksheet lookup failed. Worksheet is not created properly.");
}

From source file:org.liberty.android.fantastischmemo.downloader.google.DocumentFactory.java

public static void deleteDocument(Document document, String authToken) throws IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files/" + document.getId());
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "Bearer " + authToken);

    conn.setRequestMethod("DELETE");

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }//from   w ww  . j a va 2  s . c  om
}

From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java

public static boolean verify(String recaptchaResponse, String secret) {
    if (StringUtils.isNullOrEmpty(recaptchaResponse)) {
        return false;
    }/*from ww  w  .j  a v  a  2s. c  om*/

    boolean result = false;
    try {
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // add request header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + recaptchaResponse;
        //            log.debug("Post parameters '{}'", postParams);

        // send post request
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(postParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        log.debug("Response code '{}'", responseCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // print result
        log.debug("Response '{}'", response.toString());

        // parse JSON response and return 'success' value
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response.toString());
        JsonNode nameNode = rootNode.path("success");

        result = nameNode.asBoolean();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return result;
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String testIt(String https_url, Map<String, String> map, String method)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL url;//from  w  w w  . j  a  v a 2  s  . c o  m
    try {

        url = new URL(https_url);

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setRequestMethod(method);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            con.setRequestProperty(entry.getKey(), entry.getValue());
        }

        con.setSSLSocketFactory(ssf);
        //dumpl all cert info
        //print_https_cert(con);
        //dump all the content
        return print_content(con);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

private static String getData(String target, String method, String token) {
    try {/*www.j  a  v  a 2s. c  o m*/
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token))
            conn.setRequestProperty("Authorization", token);

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null)
            data += line;
        in.close();

        return data;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return null;
}

From source file:org.liberty.android.fantastischmemo.downloader.google.CellsFactory.java

public static void uploadCells(Spreadsheet spreadsheet, Worksheet worksheet, Cells cells, String authToken)
        throws IOException {
    URL url = new URL("https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full/batch?access_token=" + authToken);
    String urlPrefix = "https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full";

    for (int r = 0; r < cells.getRowCounts(); r += MAX_BATCH_SIZE) {
        int upBound = Math.min(r + MAX_BATCH_SIZE, cells.getRowCounts());

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);/*w  w w. ja  v a  2  s  . c om*/
        conn.setDoOutput(true);
        conn.addRequestProperty("Content-Type", "application/atom+xml");
        //conn.addRequestProperty("Content-Length", "" + payload.length());
        conn.addRequestProperty("If-Match", "*");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

        StringBuilder head = new StringBuilder();
        head.append("<?xml version='1.0' encoding='UTF-8'?>");
        head.append(
                "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:batch=\"http://schemas.google.com/gdata/batch\" xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">");
        head.append("<id>" + urlPrefix + "</id>");

        out.write(head.toString());

        for (int i = r; i < upBound; i++) {
            List<String> row = cells.getRow(i);
            for (int j = 0; j < row.size(); j++) {
                out.write(getEntryToRequesetString(urlPrefix, i + 1, j + 1, row.get(j)));
            }
        }
        out.write("</feed>");

        out.close();
        if (conn.getResponseCode() / 100 >= 3) {
            String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
            throw new IOException(s);
        }
    }
}