Example usage for javax.net.ssl HttpsURLConnection setDoInput

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

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

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);
    conn.setDoOutput(true);//w w  w  . jav a 2 s .c  o  m
    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.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);
    conn.setDoOutput(true);//from  ww w  .ja v  a  2 s . c  om
    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);
    conn.setDoOutput(true);/*from  w w  w.j a v  a2 s .  com*/
    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);
    conn.setDoOutput(true);// w w w .ja v  a 2 s.  c o  m
    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.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);
        conn.setDoOutput(true);/*from  w  w  w .  ja v a2s .  co  m*/
        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);
        }
    }
}

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

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //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();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/* w  w w  .j a  v a2  s . c  o m*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod(method);/* ww  w. ja va 2  s  . c om*/
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
    conn.setRequestProperty("User-Agent", "stargate");
    conn.setRequestProperty("Content-Type", ctype);
    return conn;
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.AuthContextAPIClient.java

/**
 * Send mutual ssl https post request and return data
 *
 * @param backendURL   URL of the service
 * @return Received data/*from  w  ww  .j a v  a 2  s  .  c  o  m*/
 * @throws IOException
 */
public static String getContextProperties(String backendURL) {
    InputStream inputStream = null;
    BufferedReader reader = null;
    String response = null;
    URL url = null;

    try {
        url = new URL(backendURL);
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
        httpsURLConnection.setSSLSocketFactory(MutualSSLManager.getSslSocketFactory());
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setRequestMethod(HTTP_METHOD_GET);

        httpsURLConnection.setRequestProperty(MutualSSLManager.getUsernameHeaderName(),
                MutualSSLManager.getCarbonLogin());

        inputStream = httpsURLConnection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line;

        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            builder.append(line);
        }
        response = builder.toString();
    } catch (IOException e) {
        log.error("Sending " + HTTP_METHOD_GET + " request to URL : " + url + "failed.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }

        } catch (IOException e) {
            log.error("Closing stream for " + url + " failed", e);
        }
    }
    return response;
}

From source file:com.illusionaryone.TwitchTMIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, boolean isArray) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;/* ww  w .  jav  a  2 s.com*/
    HttpsURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        if (isArray) {
            jsonResult = new JSONObject("{ \"array\": " + jsonText + " }");
        } else {
            jsonResult = new JSONObject(jsonText);
        }
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.illusionaryone.BTTVAPIv2.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//from   w  w  w . ja  v a2  s .c  o m
    HttpsURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.printStackTrace(ex);
            }
    }

    return (jsonResult);
}