Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public void one_set(String mg_name, List<QueryResult> counters) {
    HttpURLConnection urlCxn = null;
    URL newurl = null;/*from  w  w  w .j a  v a2s  . c om*/
    try {
        newurl = new URL(url_str + "/samples/" + mg_name + ".json");
        if (proxy == null) {
            urlCxn = (HttpURLConnection) newurl.openConnection();
        } else {
            urlCxn = (HttpURLConnection) newurl.openConnection(proxy);
        }
        if (urlCxn != null) {
            urlCxn.setRequestMethod("POST");
            urlCxn.setDoInput(true);
            urlCxn.setDoOutput(true);
            urlCxn.setReadTimeout(coppereggApiTimeoutInMillis);
            urlCxn.setRequestProperty("content-type", "application/json; charset=utf-8");
            urlCxn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception: one_set: failed to connect to CopperEgg Service '{}' with proxy {}", newurl,
                proxy, e);
        return;
    }
    if (urlCxn != null) {
        try {
            cue_serialize(counters, urlCxn.getOutputStream());
            int responseCode = urlCxn.getResponseCode();
            if (responseCode != 200) {
                logger.warn("one_set: Failure {}: {} to send result to CopperEgg service {}", responseCode,
                        urlCxn.getResponseMessage(), newurl);
            }
            try {
                InputStream in = urlCxn.getInputStream();
                IoUtils2.copy(in, IoUtils2.nullOutputStream());
                IoUtils2.closeQuietly(in);
                InputStream err = urlCxn.getErrorStream();
                if (err != null) {
                    IoUtils2.copy(err, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(err);
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Execption one_set: Write-Exception flushing http connection", e);
            }

        } catch (Exception e) {
            exceptionCounter.incrementAndGet();
            logger.warn("Execption: one_set: Failure to send result to CopperEgg Service '{}' with proxy {}",
                    newurl, proxy, e);
        }
    }
}

From source file:se.vgregion.service.barium.BariumRestClientImpl.java

private String doRequest(String method, String uri, byte[] data, int methodCallCount) throws BariumException {

    LOGGER.debug("doRequest: apiLocation: " + apiLocation + ", method: " + method + ", uri: " + uri + ", data: "
            + (data != null ? new String(data) : ""));

    URL url;//from  ww  w. j a  va 2 s.c om
    HttpURLConnection conn = null;
    String response = null;

    InputStream inputStream = null;
    BufferedInputStream bis = null;

    OutputStream outputStream = null;
    BufferedOutputStream bos = null;
    try {
        if (method.equalsIgnoreCase("POST")) {
            if (uri != null) {
                url = new URL(this.apiLocation + uri);
            } else {
                throw new RuntimeException("For POST requests a uri is expected.");
            }
        } else {
            url = new URL(this.apiLocation + uri);
        }

        //            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(8888));
        conn = (HttpURLConnection) url.openConnection(/*proxy*/);
        conn.setConnectTimeout(120000);
        conn.setReadTimeout(120000);
        if (ticket != null) {
            conn.setRequestProperty("ticket", ticket);
        } else if (!uri.contains("authenticate")) {
            this.connect();
            conn.setRequestProperty("ticket", ticket);
        }
        conn.setRequestMethod(method);
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        if (method.equalsIgnoreCase("POST")) {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            outputStream = conn.getOutputStream();
            bos = new BufferedOutputStream(outputStream);

            bos.write(data);
            bos.flush();
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
            ticket = null; // We weren't authorized, possibly due to an old ticket.
            this.connect();
            if (methodCallCount <= 3) {
                return doRequest(method, uri, data, ++methodCallCount);
            } else {
                String msg = "Error - Unable to authenticate to Barium: " + uri;
                readResponseAndThrowBariumException(conn, msg);
            }
        } else if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            if (methodCallCount <= 3) {
                return doRequest(method, uri, data, ++methodCallCount);
            } else {
                String msg = "Error - Internal Server Error - From Barium - for idea: " + uri;
                readResponseAndThrowBariumException(conn, msg);
            }
        }

        inputStream = conn.getInputStream();
        bis = new BufferedInputStream(inputStream);

        response = toString(bis);
    } catch (IOException e) {

        if (conn != null) {
            inputStream = conn.getErrorStream();
            bis = new BufferedInputStream(inputStream);
            try {
                response = toString(bis);
            } catch (Exception e2) {
                LOGGER.error(e2.getMessage(), e2);
            }
            throw new BariumException(response, e);
        }
    } finally {
        Util.closeClosables(bis, inputStream, bos, outputStream);
    }
    LOGGER.debug("Response: " + response);
    return response;
}

From source file:com.trk.aboutme.facebook.Request.java

final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
        throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();//from   w w w .jav  a2  s . co m
        return;
    }

    connection.setDoOutput(true);

    BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
    try {
        Serializer serializer = new Serializer(outputStream, logger);

        if (numRequests == 1) {
            Request request = requests.get(0);

            logger.append("  Parameters:\n");
            serializeParameters(request.parameters, serializer);

            logger.append("  Attachments:\n");
            serializeAttachments(request.parameters, serializer);

            if (request.graphObject != null) {
                processGraphObject(request.graphObject, url.getPath(), serializer);
            }
        } else {
            String batchAppID = getBatchAppId(requests);
            if (Utility.isNullOrEmpty(batchAppID)) {
                throw new FacebookException("At least one request in a batch must have an open Session, or a "
                        + "default app ID must be specified.");
            }

            serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);

            // We write out all the requests as JSON, remembering which file attachments they have, then
            // write out the attachments.
            Bundle attachments = new Bundle();
            serializeRequestsAsJSON(serializer, requests, attachments);

            logger.append("  Attachments:\n");
            serializeAttachments(attachments, serializer);
        }
    } finally {
        outputStream.close();
    }

    logger.log();
}

From source file:com.micro.http.MicroHttpClient.java

/**
  * ?,???String,?????//from w  w  w . ja  v  a 2  s.c  o m
  * @param url
  * @param params
  * @return
  */
public void doRequest(final String url, final MicroRequestParams params,
        final MicroStringHttpResponseListener responseListener) {
    responseListener.setHandler(new ResponderHandler(responseListener));
    mExecutorService.execute(new Runnable() {
        public void run() {
            HttpURLConnection urlConn = null;
            try {
                responseListener.sendStartMessage();

                if (!A.isNetworkAvailable(mContext)) {
                    Thread.sleep(200);
                    responseListener.sendFailureMessage(MicroHttpStatus.CONNECT_FAILURE_CODE,
                            MicroAppConfig.CONNECT_EXCEPTION,
                            new MicroAppException(MicroAppConfig.CONNECT_EXCEPTION));
                    return;
                }

                String resultString = null;
                URL requestUrl = new URL(url);
                urlConn = (HttpURLConnection) requestUrl.openConnection();
                urlConn.setRequestMethod("POST");
                urlConn.setConnectTimeout(mTimeout);
                urlConn.setReadTimeout(mTimeout);
                urlConn.setDoOutput(true);

                if (params != null) {
                    urlConn.setRequestProperty("connection", "keep-alive");
                    urlConn.setRequestProperty("Content-Type",
                            "multipart/form-data; boundary=" + params.boundaryString());
                    MultipartEntity reqEntity = params.getMultiPart();
                    reqEntity.writeTo(urlConn.getOutputStream());
                } else {
                    urlConn.connect();
                }

                if (urlConn.getResponseCode() == HttpStatus.SC_OK) {
                    resultString = readString(urlConn.getInputStream());
                } else {
                    resultString = readString(urlConn.getErrorStream());
                }
                resultString = URLEncoder.encode(resultString, encode);
                urlConn.getInputStream().close();
                responseListener.sendSuccessMessage(MicroHttpStatus.SUCCESS_CODE, resultString);
            } catch (Exception e) {
                e.printStackTrace();
                L.I("[HTTP POST]:" + url + ",error" + e.getMessage());
                //???
                responseListener.sendFailureMessage(MicroHttpStatus.UNTREATED_CODE, e.getMessage(),
                        new MicroAppException(e));
            } finally {
                if (urlConn != null)
                    urlConn.disconnect();

                responseListener.sendFinishMessage();
            }
        }
    });
}

From source file:com.sandklef.coachapp.http.HttpAccess.java

public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName)
        throws HttpAccessException, IOException {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR
            + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR
            + HttpSettings.UPLOAD_PATH;/*from   w ww  .  j a v a  2 s.com*/

    Log.d(LOG_TAG, "Upload server url: " + urlServer);
    Log.d(LOG_TAG, "Upload file:       " + fileName);

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;

    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    Log.d(LOG_TAG, "connection: " + connection + "  uploading data to video: " + videoUuid);

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod(HttpSettings.HTTP_POST);

    //
    int timeout = LocalStorage.getInstance().getnetworkTimeout();
    Log.d(LOG_TAG, "timeout: " + timeout);
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);

    connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken());
    connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub());
    connection.setRequestProperty("Connection", "close");

    Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties());

    outputStream = new DataOutputStream(connection.getOutputStream());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        Log.d(LOG_TAG, " writing data to stream  (" + bytesRead + " / " + bytesAvailable + ")");
        outputStream.write(buffer, 0, bufferSize);
        Log.d(LOG_TAG, " writing data to stream  -");
        bytesAvailable = fileInputStream.available();
        Log.d(LOG_TAG, " writing data to stream  -");
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    outputStream.flush();
    outputStream.close();

    // Responses from the server (code and message)
    fileInputStream.close();

    int serverResponseCode = 0;

    long before = System.currentTimeMillis();
    try {
        Log.d(LOG_TAG, " ... writing done, getting response code");
        serverResponseCode = connection.getResponseCode();
        Log.d(LOG_TAG, " ... writing done, getting response message");
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG, "ServerCode:" + serverResponseCode);
        Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage);
    } catch (java.net.SocketTimeoutException e) {
        Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace");
        e.printStackTrace();
        throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW);
    }
    long after = System.currentTimeMillis();
    long diff = after - before;
    Log.d(LOG_TAG, "diff: " + diff + "ms   " + diff / 1000 + "s");

    if (diff > LocalStorage.getInstance().getnetworkTimeout()) {
        throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW);
    }

    if (serverResponseCode >= 409) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.CONFLICT_ERROR);
    }

    if (serverResponseCode < 500 && serverResponseCode >= 400) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.ACCESS_ERROR);
    }

    try {
        Log.d(LOG_TAG, " ... disconnecting");
        connection.disconnect();
    } catch (Exception e) {
        Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace");
        e.printStackTrace();
    }
}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param connectUrl/*from  w ww.j  av a  2 s.  c  o m*/
 * @return
 * @throws IOException
 * @throws DAOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private HttpURLConnection openUrlConnection(String connectUrl)
        throws IOException, DAOException, SAXException, ParserConfigurationException {

    String sanitizedUrl = StringUtils.substringBefore(connectUrl, "#");
    sanitizedUrl = StringUtils.replace(sanitizedUrl, " ", "%20");

    HttpURLConnection connection = (HttpURLConnection) new URL(sanitizedUrl).openConnection();
    connection.setRequestProperty("Accept", ACCEPT_HEADER);
    connection.setRequestProperty("User-Agent", URLUtil.userAgentHeader());
    connection.setRequestProperty("Connection", "close");
    connection.setInstanceFollowRedirects(false);

    // Set the timeout both for establishing the connection, and reading from it once established.
    int httpTimeout = GeneralConfig.getIntProperty(GeneralConfig.HARVESTER_HTTP_TIMEOUT, getTimeout());
    connection.setConnectTimeout(httpTimeout);
    connection.setReadTimeout(httpTimeout);

    // Use "If-Modified-Since" header, if this is not an on-demand harvest
    if (!isOnDemandHarvest) {

        // "If-Modified-Since" will be compared to this URL's last harvest
        Date lastHarvestDate = getContextSourceDTO().getLastHarvest();
        long lastHarvest = lastHarvestDate == null ? 0L : lastHarvestDate.getTime();
        if (lastHarvest > 0) {

            // Check if this URL has a conversion stylesheet, and if the latter has been modified since last harvest.
            String conversionStylesheetUrl = getConversionStylesheetUrl(sanitizedUrl);
            boolean hasConversion = !StringUtils.isBlank(conversionStylesheetUrl);
            boolean hasModifiedConversion = hasConversion
                    && URLUtil.isModifiedSince(conversionStylesheetUrl, lastHarvest);

            // Check if post-harvest scripts are updated
            boolean scriptsModified = DAOFactory.get().getDao(PostHarvestScriptDAO.class)
                    .isScriptsModified(lastHarvestDate, getContextSourceDTO().getUrl());

            // "If-Modified-Since" should only be set if there is no modified conversion or post-harvest scripts for this URL.
            // Because if there is a conversion stylesheet or post-harvest scripts, and any of them has been modified since last
            // harvest, we surely want to get the content again and run the conversion or script on the content, regardless of
            // when the content itself was last modified.
            if (!hasModifiedConversion && !scriptsModified) {
                LOGGER.debug(loggerMsg(
                        "Using if-modified-since, compared to last harvest " + formatDate(lastHarvestDate)));
                connection.setIfModifiedSince(lastHarvest);
            }
        }
    }

    return connection;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {/* ww w .j  a  v a  2s.c  om*/
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}

From source file:cn.org.eshow.framwork.http.AbHttpClient.java

/**
  * ?,???String,?????//from  ww  w  .  ja va 2 s .  c  o m
  * @param url
  * @param params
  * @return
  */
public void doRequest(final String url, final AbRequestParams params,
        final AbStringHttpResponseListener responseListener) {
    responseListener.setHandler(new ResponderHandler(responseListener));
    mExecutorService.execute(new Runnable() {
        public void run() {
            HttpURLConnection urlConn = null;
            try {
                responseListener.sendStartMessage();

                if (!AbAppUtil.isNetworkAvailable(mContext)) {
                    Thread.sleep(200);
                    responseListener.sendFailureMessage(AbHttpStatus.CONNECT_FAILURE_CODE,
                            AbAppConfig.CONNECT_EXCEPTION, new AbAppException(AbAppConfig.CONNECT_EXCEPTION));
                    return;
                }

                String resultString = null;
                URL requestUrl = new URL(url);
                urlConn = (HttpURLConnection) requestUrl.openConnection();
                urlConn.setRequestMethod("POST");
                urlConn.setConnectTimeout(mTimeout);
                urlConn.setReadTimeout(mTimeout);
                urlConn.setDoOutput(true);

                if (params != null) {
                    urlConn.setRequestProperty("connection", "keep-alive");
                    urlConn.setRequestProperty("Content-Type",
                            "multipart/form-data; boundary=" + params.boundaryString());
                    MultipartEntity reqEntity = params.getMultiPart();
                    reqEntity.writeTo(urlConn.getOutputStream());
                } else {
                    urlConn.connect();
                }

                if (urlConn.getResponseCode() == HttpStatus.SC_OK) {
                    resultString = readString(urlConn.getInputStream());
                } else {
                    resultString = readString(urlConn.getErrorStream());
                }
                resultString = URLEncoder.encode(resultString, encode);
                urlConn.getInputStream().close();
                responseListener.sendSuccessMessage(AbHttpStatus.SUCCESS_CODE, resultString);
            } catch (Exception e) {
                e.printStackTrace();
                AbLogUtil.i(mContext, "[HTTP POST]:" + url + ",error" + e.getMessage());
                //???
                responseListener.sendFailureMessage(AbHttpStatus.UNTREATED_CODE, e.getMessage(),
                        new AbAppException(e));
            } finally {
                if (urlConn != null)
                    urlConn.disconnect();

                responseListener.sendFinishMessage();
            }
        }
    });
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*w w  w . j  a v a2s .  c o  m*/
    }
    URL url = new URL(request.getRequestLine().getUri());

    HttpURLConnection conn = null;

    Proxy proxy = null;
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);

    if (!isRunning)
        return;

    try {
        client.getOutputStream().write(
                ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes());

        if (conn.getResponseCode() == 200 && conn.getInputStream() != null) {
            byte[] buff = new byte[8192];
            int readBytes;
            while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) {
                client.getOutputStream().write(buff, 0, readBytes);
            }
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }

    conn.disconnect();
    stop();
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private String sendForm(String target_url, Map<String, String> arguments, String method,
        List<Cookie> cookielist) {
    try {//from w w  w . ja  v a2  s  .co m
        URL url = new URL(target_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //HttpURLConnection http = (HttpURLConnection)con;
        con.setRequestMethod(method); // PUT is another valid option
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        String cookiestr = "";
        if (cookielist != null) {
            if (cookielist.size() > 0) {
                for (Cookie cookie : cookielist) {
                    if (!cookiestr.equals("")) {
                        cookiestr += ";" + cookie.getName() + "=" + cookie.getValue();
                    } else {
                        cookiestr += cookie.getName() + "=" + cookie.getValue();
                    }
                }
                con.setRequestProperty("Cookie", cookiestr);
            }
        }

        con.setReadTimeout(5000);

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        con.setFixedLengthStreamingMode(length);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.setRequestProperty("Accept-Language", "en-us;");
        con.connect();
        try (OutputStream os = con.getOutputStream()) {
            os.write(out);
            os.close();
        }

        boolean redirect = false;
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            String newURL = con.getHeaderField("Location");
            String cookies = con.getHeaderField("Set-Cookie");
            if (cookies == null) {
                cookies = cookiestr;
            }
            con = (HttpURLConnection) new URL(newURL).openConnection();
            con.setRequestProperty("Cookie", cookies);
        }

        InputStream is = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray(), Charset.forName("UTF-8"));
        con.disconnect();

        return data;

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}