Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:cms.service.util.ItemUtility.java

public String sendPost(String url, String urlParams) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);// w w w  .j a  v a 2s  . co  m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParams);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    logger.info("\nSending 'POST' request to URL : " + url);
    logger.info("Post parameters : " + urlParams);
    logger.info("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);
    }
    in.close();

    //print result
    return (response.toString());

}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getResultFromHttp(final String location, final JSONObject object)
        throws ExternalDbUnavailableException {
    HttpURLConnection conn = null;
    try {/*from www  .  jav a 2s. c  o  m*/
        URL url = new URL(location);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);

        OutputStreamWriter stream = new OutputStreamWriter(conn.getOutputStream(), Charset.defaultCharset());
        stream.write(object.toString());
        stream.flush();

        int status = conn.getResponseCode();

        while (true) {
            String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER);
            long wait = 0;

            if (header != null) {
                wait = Integer.valueOf(header);
            }

            if (wait == 0) {
                break;
            }

            LOGGER.info(String.format(WAITING_FORMAT, wait));
            conn.disconnect();

            Thread.sleep(wait * MILLIS_IN_SECOND);

            conn = (HttpURLConnection) new URL(location).openConnection();
            conn.setDoInput(true);
            conn.connect();
            status = conn.getResponseCode();
        }
        return getHttpResult(status, location, conn);
    } catch (IOException | InterruptedException | ExternalDbUnavailableException e) {
        throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e);

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

}

From source file:com.zzl.zl_app.cache.Utility.java

public static String uploadFile(File file, String RequestURL, String fileName) {
    Tools.log("IO", "RequestURL:" + RequestURL);
    String result = null;/*from   www .j a v  a2 s. c  o m*/
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT);
        conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            Tools.log("FileSize", "file:" + file.length());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
                Tools.log("FileSize", "size:" + len);
            }

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            dos.close();
            is.close();
            /**
             * ??? 200=? ?????
             */
            int res = conn.getResponseCode();
            Tools.log("IO", "ResponseCode:" + res);
            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
            }

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

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

private void connectAndSend(String xml) throws ServerException {

    HttpURLConnection conn = null;
    OutputStreamWriter wr = null;

    try {/*w  ww . ja va2  s.  co  m*/
        LOGGER.debug("{} - Url: {}", instanceName, urlstr);
        String payload = cmd + xml;
        conn = createHTTPConnection(payload);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payload);
        wr.flush();

        /*
         * Look for status != 0 by building a DOM to parse
         * <status>0</status> <message>OK</message>
         */

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGGER.error("{} - Could not get a doc builder", instanceName, e);
            return;
        }

        /*
         * Getting the value for status and message tags
         */
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NRDP return string - {}", convertStreamToString(is));
                is.reset();
            }

            Document doc = null;

            doc = dBuilder.parse(is);

            doc.getDocumentElement().normalize();
            String rootNode = doc.getDocumentElement().getNodeName();
            NodeList responselist = doc.getElementsByTagName(rootNode);
            String result = (String) ((Element) responselist.item(0)).getElementsByTagName("status").item(0)
                    .getChildNodes().item(0).getNodeValue().trim();

            LOGGER.debug("NRDP return status is: {}", result);

            if (!"0".equals(result)) {
                String message = (String) ((Element) responselist.item(0)).getElementsByTagName("message")
                        .item(0).getChildNodes().item(0).getNodeValue().trim();
                LOGGER.error("{} - nrdp returned message \"{}\" for xml: {}", instanceName, message, xml);
            }
        } catch (SAXException e) {
            LOGGER.error("{} - Could not parse response xml", instanceName, e);
        }

    } catch (IOException e) {
        LOGGER.error("{} - Network error - check nrdp server and that service is started", instanceName, e);
        throw new ServerException(e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException ignore) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:loadTest.loadTestLib.LUtil.java

public boolean startDockerSlave(LoadTestConfigModel ltModel) throws InterruptedException, IOException {

    String fileCount = String.valueOf(ltModel.getFileCount());

    if (runInDockerCluster) {
        HashMap<String, Integer> dockerNodes = getDockerNodes();

        Entry<String, Integer> entry = this.getLowestDockerHost();

        startedClusterContainer.put(entry.getKey(), entry.getValue() + 1);

        String dockerCommand = "{" + "\"Hostname\":\"\"," + "\"User\":\"\","
                + "\"Entrypoint\":[\"/bin/bash\",\"/pieShare/pieShareAppIntegrationTests/src/test/resources/docker/internal.sh\"],"
                + "\"Cmd\":[\"slave\",\"" + fileCount.toString() + "\"]," + "\"Memory\":0,"
                + "\"MemorySwap\":0," + "\"AttachStdin\":false," + "\"AttachStdout\":false,"
                + "\"AttachStderr\":false," + "\"PortSpecs\":null," + "\"Privileged\": false,"
                + "\"Tty\":false," + "\"OpenStdin\":false," + "\"StdinOnce\":false," + "\"Env\":null,"
                + "\"Dns\":null," + "\"Image\":\"vauvenal5/loadtest\"," + "\"Volumes\":{},"
                + "\"VolumesFrom\":\"\"," + "\"WorkingDir\":\"\"}";

        String url = entry.getKey() + "/containers/create";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");
        con.setDoOutput(true);//  w  w w  .  ja va  2 s .  c  o m
        con.getOutputStream().write(dockerCommand.getBytes());
        con.getOutputStream().flush();
        con.getOutputStream().close();

        int responseCode = con.getResponseCode();

        if (responseCode != 201) {
            return false;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        String msg = "";

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

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(msg);

        String containerId = node.get("Id").asText();
        con.disconnect();

        url = entry.getKey() + "/containers/" + containerId + "/start";
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");

        responseCode = con.getResponseCode();

        if (responseCode != 204) {
            return false;
        }

        if (!this.runningContainers.containsKey(entry.getKey())) {
            this.runningContainers.put(entry.getKey(), new ArrayList<>());
        }

        this.runningContainers.get(entry.getKey()).add(containerId);

        return true;
    }

    ProcessBuilder processBuilder = new ProcessBuilder("docker", "run", "vauvenal5/loadtest", "slave",
            fileCount);
    Process proc = processBuilder.start();
    this.slaves.add(proc);
    return true;
}

From source file:com.pursuer.reader.easyrss.network.NetworkClient.java

public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException {
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(40 * 1000);//from w  w  w.j  a v  a  2 s .  c  o  m
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }
    conn.setDoInput(true);
    conn.setDoOutput(true);
    final OutputStream output = conn.getOutputStream();
    output.write(params.getBytes());
    output.flush();
    output.close();

    conn.connect();
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final IOException exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

From source file:com.paymaya.sdk.android.common.network.AndroidClient.java

@Override
public Response call(Request request) {
    HttpURLConnection conn = initializeConnection(request);
    try {/*from   ww w  .j a v a  2 s  .  c  o  m*/
        switch (request.getMethod()) {
        case GET:
            conn.setRequestMethod("GET");
            break;
        case POST:
            conn.setRequestMethod("POST");
            break;
        default:
            throw new RuntimeException("Invalid method " + request.getMethod());
        }
        if (request.getBody() != null) {
            conn.setDoOutput(true);
            write(conn.getOutputStream(), request.getBody());
        }
        int code = conn.getResponseCode();
        String message = conn.getResponseMessage();
        String response;
        if (code < 200 || code > 299) {
            response = read(conn.getErrorStream());
        } else {
            response = read(conn.getInputStream());
        }

        Log.d(TAG, "Status: " + code + " " + message);
        Log.d(TAG, "Response: " + new JSONObject(response).toString(2));
        return new Response(code, response);
    } catch (IOException | JSONException e) {
        Log.e(TAG, e.getMessage());
        return new Response(-1, "");
    } finally {
        conn.disconnect();
    }
}

From source file:com.example.httpjson.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/*from   w  w w .ja va 2  s.  co m*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                if (a == 401) {
                    response = new Response(a, conn.getHeaderFields(), new byte[] {});
                }
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.haulmont.cuba.core.app.filestorage.amazon.AmazonS3FileStorage.java

@Override
public long saveStream(FileDescriptor fileDescr, InputStream inputStream) throws FileStorageException {
    Preconditions.checkNotNullArgument(fileDescr.getSize());

    int chunkSize = amazonS3Config.getChunkSize();
    long fileSize = fileDescr.getSize();
    URL amazonUrl = getAmazonUrl(fileDescr);
    // set the markers indicating we're going to send the upload as a series
    // of chunks:
    //   -- 'x-amz-content-sha256' is the fixed marker indicating chunked
    //      upload
    //   -- 'content-length' becomes the total size in bytes of the upload
    //      (including chunk headers),
    //   -- 'x-amz-decoded-content-length' is used to transmit the actual
    //      length of the data payload, less chunk headers
    Map<String, String> headers = new HashMap<>();
    headers.put("x-amz-storage-class", "REDUCED_REDUNDANCY");
    headers.put("x-amz-content-sha256", AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256);
    headers.put("content-encoding", "aws-chunked");
    headers.put("x-amz-decoded-content-length", "" + fileSize);

    AWS4SignerForChunkedUpload signer = new AWS4SignerForChunkedUpload(amazonUrl, "PUT", "s3",
            amazonS3Config.getRegionName());

    // how big is the overall request stream going to be once we add the signature
    // 'headers' to each chunk?
    long totalLength = AWS4SignerForChunkedUpload.calculateChunkedContentLength(fileSize, chunkSize);
    headers.put("content-length", "" + totalLength);

    String authorization = signer.computeSignature(headers, null, // no query parameters
            AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256, amazonS3Config.getAccessKey(),
            amazonS3Config.getSecretAccessKey());

    // place the computed signature into a formatted 'Authorization' header
    // and call S3
    headers.put("Authorization", authorization);

    // start consuming the data payload in blocks which we subsequently chunk; this prefixes
    // the data with a 'chunk header' containing signature data from the prior chunk (or header
    // signing, if the first chunk) plus length and other data. Each completed chunk is
    // written to the request stream and to complete the upload, we send a final chunk with
    // a zero-length data payload.

    try {/*from  w ww.  j  a va 2 s . c  om*/
        // first set up the connection
        HttpURLConnection connection = HttpUtils.createHttpConnection(amazonUrl, "PUT", headers);

        // get the request stream and start writing the user data as chunks, as outlined
        // above;
        int bytesRead;
        byte[] buffer = new byte[chunkSize];
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        //guarantees that it will read as many bytes as possible, this may not always be the case for
        //subclasses of InputStream
        while ((bytesRead = IOUtils.read(inputStream, buffer, 0, chunkSize)) > 0) {
            // process into a chunk
            byte[] chunk = signer.constructSignedChunk(bytesRead, buffer);

            // send the chunk
            outputStream.write(chunk);
            outputStream.flush();
        }

        // last step is to send a signed zero-length chunk to complete the upload
        byte[] finalChunk = signer.constructSignedChunk(0, buffer);
        outputStream.write(finalChunk);
        outputStream.flush();
        outputStream.close();

        // make the call to Amazon S3
        HttpUtils.HttpResponse httpResponse = HttpUtils.executeHttpRequest(connection);
        if (!httpResponse.isStatusOk()) {
            String message = String.format("Could not save file %s. %s", getFileName(fileDescr),
                    getInputStreamContent(httpResponse));
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, message);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error when sending chunked upload request", e);
    }

    return fileDescr.getSize();
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Sends a POST request//w  ww  .ja  v a2 s . c  o m
 *
 * @param url           URL
 * @param postData      Post request body
 * @param encoding      Post request body encoding
 * @param contentType   Body content type
 * @param compress      If true - compress bod
 * @param readTimeout   Read timeout
 * @param socketTimeout Socket timeout
 * @return Response
 */
public static String postRequest(URL url, String postData, String encoding, String contentType,
        boolean compress, int readTimeout, int socketTimeout) {
    HttpURLConnection connection = null;
    OutputStream outputStream = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }
        if (compress) {
            connection.setRequestProperty("Content-Encoding", "gzip");
        }
        connection.setConnectTimeout(socketTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setDoOutput(true);
        connection.connect();
        if (postData != null) {
            outputStream = connection.getOutputStream();

            if (compress) {
                outputStream = new GZIPOutputStream(outputStream);
            }

            if (encoding != null) {
                IOUtils.write(postData, outputStream, encoding);
            } else {
                IOUtils.write(postData, outputStream);
            }

            if (compress) {
                ((GZIPOutputStream) outputStream).finish();
            } else {
                outputStream.flush();
            }
        }

        return IOUtils.toString(connection.getInputStream(), encoding);
    } catch (Exception ex) {
        LOG.error("Error posting request to {}, post data length={}\r\n", url, StringUtils.length(postData),
                ex);
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(outputStream);

        if (connection != null) {
            connection.disconnect();
        }
    }
}