Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static HttpURLConnection getConnectionForPublicUpload(final URL url, final String contentType)
        throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpPut.METHOD_NAME);
    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
    connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PUBLIC_READ);
    connection.setDoOutput(true);
    connection.connect();//from  w w w  .  j  av  a2s . co  m
    return connection;
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />//from w  w  w  .  j  a v a 2s . c o m
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequest(final URL url, final String post, final String contentType)
        throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doGet(String url, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(GET :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    URL myURL = new URL(url);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + url.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    //conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeJSON);
    //conn.setRequestProperty("Accept",);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP GET' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;//from   ww  w  .  j a  v  a  2s . c o  m
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:com.keepsafe.switchboard.SwitchBoard.java

/**
 * Returns a String containing the server response from a GET request
 * @param address Valid http addess./*ww w .ja va  2 s  . co  m*/
 * @param params String of params. Multiple params seperated with &. No leading ? in string
 * @return Returns String from server or null when failed.
 */
private static String readFromUrlGET(String address, String params) {
    if (address == null || params == null)
        return null;

    String completeUrl = address + "?" + params;
    if (DEBUG)
        Log.d(TAG, "readFromUrl(): " + completeUrl);

    try {
        URL url = new URL(completeUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setDoOutput(true);

        // get response
        InputStream is = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader bufferReader = new BufferedReader(inputStreamReader, 8192);
        String line = "";
        StringBuffer resultContent = new StringBuffer();
        while ((line = bufferReader.readLine()) != null) {
            if (DEBUG)
                Log.d(TAG, line);
            resultContent.append(line);
        }
        bufferReader.close();

        if (DEBUG)
            Log.d(TAG, "readFromUrl() result: " + resultContent.toString());

        return resultContent.toString();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.tohours.imo.util.TohoursUtils.java

/**
 * //from  w  w w .  jav  a 2 s  .co  m
 * @param path
 * @param charsetName
 * @param param
 * @return
 * @throws IOException
 */
public static String httpPost(String path, String param, String charsetName) throws IOException {
    String rv = null;
    URL url = null;
    HttpURLConnection conn = null;
    InputStream input = null;
    try {
        url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "plain/text");
        conn.setRequestProperty("User-Agent", "Tohours Shake Project");
        OutputStream os = conn.getOutputStream();
        os.write(param.getBytes(charsetName));
        os.flush();
        os.close();
        input = conn.getInputStream();
        rv = TohoursUtils.inputStream2String(input, charsetName);
    } finally {
        if (input != null) {
            input.close();
        }
    }
    return rv;
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() {
    Map<String, DiagnosticsStatus> statuses = new HashMap<>();

    for (String tspUrl : ServerConf.getTspUrl()) {
        try {//  w w  w .  j a va  2s . c  o  m
            URL url = new URL(tspUrl);

            log.info("Checking timestamp server status for url {}", url);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS);
            con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/timestamp-query");
            con.connect();

            log.info("Checking timestamp server con {}", con);

            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok",
                        con.getResponseCode(), con.getResponseMessage());
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            } else {
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            }

        } catch (Exception e) {
            log.warn("Timestamp status check failed {}", e);

            statuses.put(tspUrl,
                    new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl));
        }
    }
    return statuses;

}

From source file:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //Creamos un objeto JSON
    JSONObject jsonObj = new JSONObject();
    //Aadimos el nombre, apellidos y email del usuario
    jsonObj.put("nombre", nombre);
    jsonObj.put("apellidos", apellidos);
    jsonObj.put("email", email);
    //Creamos una lista para almacenar el JSON
    List l = new LinkedList();
    l.addAll(Arrays.asList(jsonObj));
    //Generamos el String JSON
    String jsonString = JSONValue.toJSONString(l);
    System.out.println("JSON GENERADO:");
    System.out.println(jsonString);
    System.out.println("");

    try {/*from   w ww .  j  a v a  2  s  .  co m*/
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:flow.visibility.tapping.OpenDaylightHelper.java

/** The function for inserting the flow */

public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) {

    StringBuffer result = new StringBuffer();

    /** Check the connection to ODP REST API page */

    try {//from w w w.  java 2s .  c o m

        if (!baseURL.contains("http")) {
            baseURL = "http://" + baseURL;
        }
        baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/"
                + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name");

        /** Create URL = base URL + container */
        URL url = new URL(baseURL);

        /** Create authentication string and encode it to Base64*/
        String authStr = user + ":" + password;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        /** Create Http connection */
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /** Set connection properties */
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /** Set JSON Post Data */
        OutputStream os = connection.getOutputStream();
        os.write(postData.toString().getBytes());
        os.close();

        /** Get the response from connection's inputStream */
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /** checking the result of REST API connection */

    if ("success".equalsIgnoreCase(result.toString())) {
        return true;
    } else {
        return false;
    }
}

From source file:brainleg.app.util.AppWeb.java

/**
 * Copied from ITNProxy/* ww w  .j  a  va 2  s  .  c  om*/
 */
private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url);

    connection.setReadTimeout(60 * 1000);
    connection.setConnectTimeout(10 * 1000);
    connection.setRequestMethod(HTTP_POST);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING));
    connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length));

    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    try {
        out.write(bytes);
        out.flush();
    } finally {
        out.close();
    }

    return connection;
}

From source file:core.Web.java

public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {/*from   w  ww .j a  va2  s .  c om*/
        // Create connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            //                connection.setRequestProperty("Accept", "application/json");
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            System.err.println("Error " + responseCode + ":" + url);
            return null;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return content;
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}