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:org.openxdata.server.servlet.DataImportServletTest.java

@Test
@Ignore("this is an integration test for localhost")
public void integrationTest() throws Exception {
    final String urlString = "http://localhost:8888/org.openxdata.server.admin.OpenXDataServerAdmin/dataimport?msisdn=2222222";
    final String userName = "dagmar";
    final String password = "dagmar";

    // open url connection
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setDoOutput(true);
    con.setDoInput(true);/*ww w.j av  a2s. c  om*/
    con.setChunkedStreamingMode(1024);

    // stuff the Authorization request header
    byte[] encodedPassword = (userName + ":" + password).getBytes();
    con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(encodedPassword)));

    // put the form data on the output stream
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeByte(new Integer(1));
    String data = "<?xml version='1.0' encoding='UTF-8' ?><cmt_lesotho_tlpp_session_report_v1 formKey=\"cmt_lesotho_tlpp_session_report_v1\" id=\"2\" name=\"Treatment literacy programme_v1\" xmlns:xf=\"http://www.w3.org/2002/xforms\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">  <name>TEEHEE</name>  <session_type>treatment_literacy_session</session_type>  <session_date>2010-04-15</session_date>  <district>berea</district>  <session_location>secondary_school</session_location>  <session_location_other/>  <session_place_name>dsds</session_place_name>  <participant_number_male>1</participant_number_male>  <participant_number_female>2</participant_number_female>  <session_start_time>10:22:00</session_start_time>  <session_finish_time>01:22:00</session_finish_time>  <session_topic>children_HIV_incl_ARVs</session_topic>  <session_topic_other/>  <support_group>false</support_group>  <one_on_one_session>false</one_on_one_session>  <CMT_AV_kit>false</CMT_AV_kit>  <CMT_DVD>false</CMT_DVD>  <CMT_co_facilitator>false</CMT_co_facilitator>  <co_facilitator_name/>  <clinic_hospital_department/>  <clinic_hospital_department_other/>  <clinic_hospital_TV/>  <school_grade>12</school_grade>  <school_CMT_materials>true</school_CMT_materials>  <session_confirmed>true</session_confirmed></cmt_lesotho_tlpp_session_report_v1>";
    out.writeUTF(data);
    out.flush();

    // pull the information back from the URL
    InputStream is = con.getInputStream();
    StringBuffer buf = new StringBuffer();
    int c;
    while ((c = is.read()) != -1) {
        buf.append((char) c);
    }
    con.disconnect();

    // output the information
    System.out.println(buf);
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie,
        Callback callback) {/*from ww  w.j  a  va2s. c o m*/
    // Declare our buffer
    ByteArrayBuffer byteArrayBuffer;

    try {
        // Setup the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString());
        if (sendCookie != null)
            urlConnection.setRequestProperty("Cookie", sendCookie);
        if (sendData != null) {
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
        }
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the output stream and send the data
        if (sendData != null) {
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(sendData.getBytes());
            outputStream.flush();
            outputStream.close();
        }

        // Get the cookie
        if (getCookie != null) {
            // Clear the string builder
            getCookie.delete(0, getCookie.length());

            // Loop thru the header fields
            String headerName;
            String cookie;
            for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) {
                if (headerName.equalsIgnoreCase("Set-Cookie")) {
                    // Get the cookie
                    cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i));

                    // Add it to the string builder
                    if (cookie != null)
                        getCookie.append(cookie);

                    break;
                }
            }
        }

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Page download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_page_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Get the file size
        final int fileSize = urlConnection.getContentLength();

        // Create our buffers
        byte[] byteBuffer = new byte[2048];
        byteArrayBuffer = new ByteArrayBuffer(2048);

        // Download the page
        int amountDownloaded = 0;
        int count;
        while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) {
            // Check if we got canceled
            if (callback.IsCancelled()) {
                inputStream.close();
                urlConnection.disconnect();
                return null;
            }

            // Add data to the buffer
            byteArrayBuffer.append(byteBuffer, 0, count);

            // Update the downloaded amount
            amountDownloaded += count;
        }

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for amount downloaded calculation error
        if (fileSize != -1 && amountDownloaded != fileSize) {
            Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not "
                    + "match reported content length (" + fileSize + " bytes).");
        }
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_download_error);
        }
        return null;
    }

    // Convert things to a string
    return new String(byteArrayBuffer.toByteArray());
}

From source file:squash.deployment.lambdas.utils.CloudFormationResponder.java

/**
 *  Sends the custom resource response to the Cloudformation service.
 *  //from  w w w  .j  a  va  2s  . c om
 *  <p>The response is returned indirectly to Cloudformation via the
 *     presigned Url it provided in its request.
 *  
 *  @param status whether the call succeeded - must be either SUCCESS or FAILED.
 *  @param logger a CloudwatchLogs logger.
 *  @throws IllegalStateException when the responder is uninitialised.
 */
public void sendResponse(String status, LambdaLogger logger) {
    if (!initialised) {
        throw new IllegalStateException("The responder has not been initialised");
    }

    try {
        rootNode.put("Status", status);
        rootNode.put("RequestId", requestParameters.get("RequestId"));
        rootNode.put("StackId", requestParameters.get("StackId"));
        rootNode.put("LogicalResourceId", requestParameters.get("LogicalResourceId"));
        rootNode.put("PhysicalResourceId", physicalResourceId);
    } catch (Exception e) {
        // Can do nothing more than log the error and return. Must rely on
        // CloudFormation timing-out since it won't get a response from us.
        logger.log("Exception caught whilst constructing response: " + e.toString());
        return;
    }

    // Send the response to CloudFormation via the provided presigned S3 URL
    logger.log("About to send response to presigned URL: " + requestParameters.get("ResponseURL"));
    try {
        URL url = new URL(requestParameters.get("ResponseURL"));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        mapper.writeTree(generator, rootNode);
        String output = cloudFormationJsonResponse.toString(StandardCharsets.UTF_8.name());

        logger.log("Response about to be sent: " + output);
        out.write(output);
        out.close();
        logger.log("Sent response to presigned URL");
        int responseCode = connection.getResponseCode();
        logger.log("Response Code returned from presigned URL: " + responseCode);
    } catch (IOException e) {
        // Can do nothing more than log the error and return.
        logger.log("Exception caught whilst replying to presigned URL: " + e.toString());
        return;
    }
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromHttpToFile(String theURL, String theParameters, String theFile) throws IOException {
    // both in milliseconds
    //int connectionTimeout = 1000 * 60 * 3;
    //int readTimeout = 1000 * 60 * 3;
    try {/*from w w w. j  a  va2s.co  m*/
        URL myURL = new URL(theURL);
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        //connection.setRequestProperty("charset", "utf-8");
        if (null != theParameters) {
            System.out.println("Content-Length " + Integer.toString(theParameters.getBytes().length));
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(theParameters.getBytes().length));
        }
        connection.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            if (null != theParameters) {
                wr.write(theParameters.getBytes());
            }
            wr.flush();
            File myFile = new File(theFile);
            System.out.println("Requesting " + myURL);
            FileUtils.copyInputStreamToFile(connection.getInputStream(), myFile);
            System.out.println("Downloaded " + myURL);
        } catch (IOException rethrownExp) {
            InputStream errorStr = connection.getErrorStream();
            if (null != errorStr) {
                System.err.println("Error stream returned: " + IOUtils.toString(errorStr));
            } else {
                System.err.println("No error stream returned");
            }
            throw rethrownExp;
        }
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage() + " thrown while downloading " + theURL
                + " to " + theFile);
        throw rethrownExp;
    }
}

From source file:gsi.twitter.StreetLocator.java

/**
 * Sends a request to the specified URL and obtains the result from the sever.
 *
 * @param url The URL to connect to//from  ww w  .  java2  s  . c  om
 * @return the server response
 * @throws IOException
 */
private String getResult(URL url) throws IOException {
    // Log.d("Locator", url.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    InputStream is = conn.getInputStream();
    String result = toString(is);
    return result;
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java

/**
 * Post data/*from   ww w .  j  av a  2 s  .  c o m*/
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    OutputStream outStream = null;
    try {
        outStream = conn.getOutputStream();
        writer = new OutputStreamWriter(outStream, "UTF-8");
        writer.write(data);
        writer.flush();
    } finally {
        if (outStream != null) {
            try {
                outStream.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);/*from  w ww. j av a2 s .  c o  m*/
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:com.baidu.jprotobuf.rpc.client.SimpleHttpRequestExecutor.java

/**
 * Prepare the given HTTP connection.//from  www .  ja va2  s  . c  o m
 * <p>The default implementation specifies POST as method,
 * "application/x-java-serialized-object" as "Content-Type" header,
 * and the given content length as "Content-Length" header.
 * @param con the HTTP connection to prepare
 * @param contentLength the length of the content to send
 * @throws IOException if thrown by HttpURLConnection methods
 * @see java.net.HttpURLConnection#setRequestMethod
 * @see java.net.HttpURLConnection#setRequestProperty
 */
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {
    con.setDoOutput(true);
    con.setRequestMethod(HTTP_METHOD_POST);
    con.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
    con.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));
    LocaleContext locale = LocaleContextHolder.getLocaleContext();
    if (locale != null) {
        con.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale.getLocale()));
    }
    if (isAcceptGzipEncoding()) {
        con.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }
}

From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java

@Override
public void run() {
    debug("THREAD STARTED");
    long start = getNow();
    while (start + TIMEOUT <= getNow() && player == null) {
    }//from  w  w w . j  a  v  a  2s.c o  m
    this.stopThread();
    this.deregister();
    if (player == null)
        return;

    boolean alreadyActivated = false;
    boolean isActivated = false;

    try {
        String x = player.getSavedVariable("xenforo");
        alreadyActivated = x.equalsIgnoreCase("yes");
    } catch (Exception e) {
    }

    try {
        String url = XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "") + APPEND;
        if (url.equals(APPEND))
            return;

        String encodedData = "name=" + encode("username") + "&value=" + encode(this.player.getPlayer())
                + "&_xfResponseType=json";
        //String rawData = "name=username";
        String type = "application/x-www-form-urlencoded; charset=UTF-8";
        //String encodedData = URLEncoder.encode(rawData, "ISO-8859-1"); 
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", type);
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Referer", XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", ""));
        conn.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(encodedData);
        wr.flush();

        InputStream in = conn.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        String out = responseStrBuilder.toString();
        JSONObject o = (JSONObject) JSONValue.parse(out);
        try {
            isActivated = o.get("_redirectMessage").toString().equalsIgnoreCase("ok");
        } catch (NullPointerException e) {
            isActivated = true;
        }
        debug("GOT: " + isActivated);
    } catch (Exception e) {
        if (DebugMode)
            e.printStackTrace();
        return;
    }

    player.setSavedVariable("xenforo", (isActivated ? "yes" : "no"));
    player.save();

    if (isActivated && !alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onRegistered"));
    }

    if (!isActivated && alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onDeRegistered"));
    }
}

From source file:gmusic.api.comm.HttpUrlConnector.java

private HttpURLConnection prepareConnection(URI address, boolean output, String method)
        throws URISyntaxException, IOException {
    HttpURLConnection connection = (HttpURLConnection) adjustAddress(address).toURL().openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(output);
    if (authorizationToken != null) {
        connection.setRequestProperty("Authorization",
                String.format("GoogleLogin auth=%1$s", authorizationToken));
    }//from www .  j av  a2  s  . c o  m
    return connection;
}