Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:org.runnerup.export.EndomondoSynchronizer.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;// w  w  w.ja v  a  2 s .c  om
    if ((s = connect()) != Status.OK) {
        return s;
    }

    EndomondoTrack tcx = new EndomondoTrack(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        EndomondoTrack.Summary summary = new EndomondoTrack.Summary();
        StringWriter writer = new StringWriter();
        tcx.export(mID, writer, summary);

        String workoutId = deviceId + "-" + Long.toString(mID);
        Log.e(getName(), "workoutId: " + workoutId);

        StringBuilder url = new StringBuilder();
        url.append(UPLOAD_URL).append("?authToken=").append(authToken);
        url.append("&workoutId=").append(workoutId);
        url.append("&sport=").append(summary.sport);
        url.append("&duration=").append(summary.duration);
        url.append("&distance=").append(summary.distance);
        if (summary.hr != null) {
            url.append("&heartRateAvg=").append(summary.hr.toString());
        }
        url.append("&gzip=true");
        url.append("&extendedResponse=true");

        conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Type", "application/octet-stream");
        OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream()));
        out.write(writer.getBuffer().toString().getBytes());
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        JSONObject res = parseKVP(in);
        conn.disconnect();

        Log.e(getName(), "res: " + res.toString());

        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        if (responseCode == HttpStatus.SC_OK && "OK".contentEquals(res.getString("_0"))) {
            s.activityId = mID;
            return s;
        }
        ex = new Exception(amsg);
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.runnerup.export.GarminSynchronizer.java

private Status connectOld() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;/*  w  w  w.  j  av a2s .  co m*/
    s.authMethod = Synchronizer.AuthMethod.USER_PASS;

    HttpURLConnection conn = null;

    /**
     * connect to START_URL to get cookies
     */
    conn = (HttpURLConnection) new URL(START_URL).openConnection();
    {
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        if (responseCode != HttpStatus.SC_OK) {
            Log.e(getName(), "GarminSynchronizer::connect() - got " + responseCode + ", msg: " + amsg);
        }
    }
    conn.disconnect();

    /**
     * Then login using a post
     */
    String login = LOGIN_URL;
    FormValues kv = new FormValues();
    kv.put("login", "login");
    kv.put("login:loginUsernameField", username);
    kv.put("login:password", password);
    kv.put("login:signInButton", "Sign In");
    kv.put("javax.faces.ViewState", "j_id1");

    conn = (HttpURLConnection) new URL(login).openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);

    {
        OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
        kv.write(wr);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        Log.e(getName(), "code: " + responseCode + ", msg=" + amsg);
        getCookies(conn);
    }
    conn.disconnect();

    /**
     * An finally check that all is OK
     */
    return checkLogin();
}

From source file:org.apache.streams.urls.LinkResolver.java

public void unwindLink(String url) {
    Objects.requireNonNull(linkDetails);
    Objects.requireNonNull(url);/*from  ww  w  . j a v a 2 s .c o m*/

    // Check url validity
    UrlValidator urlValidator = new UrlValidator();
    if (!urlValidator.isValid(url)) {
        linkDetails.setLinkStatus(LinkDetails.LinkStatus.MALFORMED_URL);
        return;
    }

    // Check to see if they wound up in a redirect loop,
    // IE: 'A' redirects to 'B', then 'B' redirects to 'A'
    if ((linkDetails.getRedirectCount() != null && linkDetails.getRedirectCount() > 0
            && (linkDetails.getOriginalURL().equals(url) || linkDetails.getRedirects().contains(url)))
            || (linkDetails.getRedirectCount() != null
                    && linkDetails.getRedirectCount() > MAX_ALLOWED_REDIRECTS)) {
        linkDetails.setLinkStatus(LinkDetails.LinkStatus.LOOP);
        return;
    }

    if (!linkDetails.getOriginalURL().equals(url))
        linkDetails.getRedirects().add(url);

    HttpURLConnection connection = null;

    // Store where the redirected link will go (if there is one)
    String reDirectedLink = null;

    try {
        // Turn the string into a URL
        URL thisURL = new URL(url);

        // Be sensitive to overloading domains STREAMS-77
        try {
            String host = thisURL.getHost().toLowerCase();
            if (!domainsSensitiveTo.contains(host)) {
                domainsSensitiveTo.add(host);
                long domainWait = LinkResolverHelperFunctions.waitTimeForDomain(thisURL.getHost());
                if (domainWait > 0) {
                    LOGGER.debug("Waiting for domain: {}", domainWait);
                    Thread.sleep(domainWait);
                }
            }
        } catch (Exception e) {
            // noOp
        }

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

        // now we are going to pretend that we are a browser...
        // This is the way my mac works.
        if (!BOTS_ARE_OK.contains(thisURL.getHost())) {
            connection.addRequestProperty("Host", thisURL.getHost());

            // Bots are not 'ok', so we need to spoof the headers
            for (String k : SPOOF_HTTP_HEADERS.keySet())
                connection.addRequestProperty(k, SPOOF_HTTP_HEADERS.get(k));

            // the test to seattlemamadoc.com prompted this change.
            // they auto detect bots by checking the referrer chain and the 'user-agent'
            // this broke the t.co test. t.co URLs are EXPLICITLY ok with bots
            // there is a list for URLS that behave this way at the top in BOTS_ARE_OK
            // smashew 2013-13-2013
            if (linkDetails.getRedirectCount() > 0 && BOTS_ARE_OK.contains(thisURL.getHost()))
                connection.addRequestProperty("Referrer", linkDetails.getOriginalURL());
        }

        connection.setReadTimeout(DEFAULT_HTTP_TIMEOUT);
        connection.setConnectTimeout(DEFAULT_HTTP_TIMEOUT);

        // we want to follow this behavior on our own to ensure that we are getting to the
        // proper place. This is especially true with links that are wounded by special
        // link winders,
        // IE:
        connection.setInstanceFollowRedirects(false);

        if (linkDetails.getCookies() != null)
            for (String cookie : linkDetails.getCookies())
                connection.addRequestProperty("Cookie", cookie.split(";", 1)[0]);

        connection.connect();

        linkDetails.setFinalResponseCode((long) connection.getResponseCode());

        Map<String, List<String>> headers = createCaseInsensitiveMap(connection.getHeaderFields());
        /*
         * If they want us to set cookies, well, then we will set cookies
         * Example URL:
         * http://nyti.ms/1bCpesx
         *****************************************************************/
        if (headers.containsKey(SET_COOKIE_IDENTIFIER))
            linkDetails.getCookies().add(headers.get(SET_COOKIE_IDENTIFIER).get(0));

        switch (linkDetails.getFinalResponseCode().intValue()) {
        /*
         * W3C HTTP Response Codes:
         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
         */
        case 200: // HTTP OK
            linkDetails.setFinalURL(connection.getURL().toString());
            linkDetails.setDomain(new URL(linkDetails.getFinalURL()).getHost());
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.SUCCESS);
            break;
        case 300: // Multiple choices
        case 301: // URI has been moved permanently
        case 302: // Found
        case 303: // Primarily for a HTTP Post
        case 304: // Not Modified
        case 306: // This status code is unused but in the redirect block.
        case 307: // Temporary re-direct
            /*
             * Author:
             * Smashew
             *
             * Date: 2013-11-15
             *
             * Note:
             * It is possible that we have already found our final URL. In
             * the event that we have found our final URL, we are going to
             * save this URL as long as it isn't the original URL.
             * We are still going to ask the browser to re-direct, but in the
             * case of yet another redirect, seen with the redbull test
             * this can be followed by a 304, a browser, by W3C standards would
             * still render the page with it's content, but for us to assert
             * a success, we are really hoping for a 304 message.
             *******************************************************************/
            if (!linkDetails.getOriginalURL().toLowerCase()
                    .equals(connection.getURL().toString().toLowerCase()))
                linkDetails.setFinalURL(connection.getURL().toString());
            if (!headers.containsKey(LOCATION_IDENTIFIER)) {
                LOGGER.info("Headers: {}", headers);
                linkDetails.setLinkStatus(LinkDetails.LinkStatus.REDIRECT_ERROR);
            } else {
                linkDetails.setRedirected(Boolean.TRUE);
                linkDetails.setRedirectCount(linkDetails.getRedirectCount() + 1);
                reDirectedLink = connection.getHeaderField(LOCATION_IDENTIFIER);
            }
            break;
        case 305: // User must use the specified proxy (deprecated by W3C)
            break;
        case 401: // Unauthorized (nothing we can do here)
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.UNAUTHORIZED);
            break;
        case 403: // HTTP Forbidden (Nothing we can do here)
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.FORBIDDEN);
            break;
        case 404: // Not Found (Page is not found, nothing we can do with a 404)
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.NOT_FOUND);
            break;
        case 500: // Internal Server Error
        case 501: // Not Implemented
        case 502: // Bad Gateway
        case 503: // Service Unavailable
        case 504: // Gateway Timeout
        case 505: // Version not supported
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.HTTP_ERROR_STATUS);
            break;
        default:
            LOGGER.info("Unrecognized HTTP Response Code: {}", linkDetails.getFinalResponseCode());
            linkDetails.setLinkStatus(LinkDetails.LinkStatus.NOT_FOUND);
            break;
        }
    } catch (MalformedURLException e) {
        // the URL is trash, so, it can't load it.
        linkDetails.setLinkStatus(LinkDetails.LinkStatus.MALFORMED_URL);
    } catch (IOException ex) {
        // there was an issue we are going to set to error.
        linkDetails.setLinkStatus(LinkDetails.LinkStatus.ERROR);
    } catch (Exception ex) {
        // there was an unknown issue we are going to set to exception.
        linkDetails.setLinkStatus(LinkDetails.LinkStatus.EXCEPTION);
    } finally {
        // if the connection is not null, then we need to disconnect to close any underlying resources
        if (connection != null)
            connection.disconnect();
    }

    // If there was a redirection, then we have to keep going
    // Placing this code here should help to satisfy ensuring that the connection object
    // is closed successfully.
    if (reDirectedLink != null)
        unwindLink(reDirectedLink);

}

From source file:iracing.webapi.IracingWebApi.java

private String doPostRequestUrlEncoded(boolean needForumCookie, String url, String parameters)
        throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return null;
    }//w  w w  .j  a  v  a 2 s  .co m
    if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return null;
    }
    String output = null;
    try {
        // URL of CGI-Bin script.
        URL oUrl = new URL(url);
        // URL connection channel.
        HttpURLConnection urlConn = (HttpURLConnection) oUrl.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        urlConn.addRequestProperty(COOKIE, cookie);

        // request to have the response gzipped (bringing a 3.5Mb response down to 175kb)
        urlConn.addRequestProperty("Accept-Encoding", "gzip");

        urlConn.setRequestMethod("POST");
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
        try {
            printout.writeBytes(parameters);
            printout.flush();
        } finally {
            printout.close();
        }

        output = getResponseText(urlConn);
        //            System.out.println(output);

        urlConn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

private InputStream doPost2(String urlString, List<NameValuePair> values, ByteArrayOutputStream content)
        throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    InputStream in = null;//from  w  w  w .j  a v a 2s.  c o m
    OutputStream out;
    byte[] buff;
    con.setRequestMethod("POST");
    for (int j = 0; j < values.size(); j++) {
        con.addRequestProperty(values.get(j).getName(), values.get(j).getValue());
    }
    String my_cookies = this.getCookies();
    con.addRequestProperty("Cookie", my_cookies);
    con.setDoOutput(true);
    con.setDoInput(true);
    con.connect();
    out = con.getOutputStream();
    buff = content.toByteArray();
    out.write(buff);
    out.flush();
    out.close();
    in = con.getInputStream();

    return in;
}

From source file:iracing.webapi.IracingWebApi.java

private SendPrivateMessageResult sendPrivateMessage(int customerDefinitionType, String customer, String subject,
        String message) throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }//from  w w  w  .j  ava  2  s  .  c o m
    SendPrivateMessageResult output = SendPrivateMessageResult.UNKNOWN_ERROR;
    if (!cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }
    try {
        // Make a connection
        URL url = new URL(FORUM_POST_PAGE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //multipart/form-data
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        //conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

        conn.addRequestProperty(COOKIE, cookie);

        StringBuilder data = new StringBuilder();

        // set the multipart form data parameters
        addMultipartFormData(data, "action", "sendSave");
        addMultipartFormData(data, "module", "pm");
        addMultipartFormData(data, "preview", "0");
        addMultipartFormData(data, "start", null);
        if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_ID) {
            addMultipartFormData(data, "toUsername", null);
            addMultipartFormData(data, "toUserId", customer);
        } else if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_NAME) {
            addMultipartFormData(data, "toUsername", customer);
            addMultipartFormData(data, "toUserId", null);
        }
        addMultipartFormData(data, "disa1ble_html", "on");
        addMultipartFormData(data, "attach_sig", "on");
        addMultipartFormData(data, "subject", subject);
        addMultipartFormData(data, "message", message);
        addMultipartFormData(data, "addbbcode24", "#444444");
        addMultipartFormData(data, "addbbcode26", "12");
        addMultipartFormData(data, "helpbox", "Italic Text: [i]Text[/i]  (alt+i)");

        data.append(twoHyphens).append(BOUNDRY).append(twoHyphens);
        DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
        try {
            dataOS.writeBytes(data.toString());
            dataOS.flush();
        } finally {
            dataOS.close();
        }

        conn.connect();

        if (isMaintenancePage(conn))
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s : %s",
                    responseCode, url, conn.getResponseMessage()));
        }

        String response = getResponseText(conn);
        //            System.out.println(response);

        if (response.contains("Your message was successfully sent.")) {
            output = SendPrivateMessageResult.SUCCESS;
        } else if (response.contains(
                "Could not determine the user id. Please check if you typed the username correctly and try again.")) {
            output = SendPrivateMessageResult.USER_NOT_FOUND;
        } else if (response.contains(
                "Sorry, but this users inbox is currently full and cannot receive private messages at this time.")) {
            output = SendPrivateMessageResult.MAILBOX_FULL;
        }

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * /*w  w w .  j  a  v a 2s  . co  m*/
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

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  w  w .j  a va2 s. co m*/

    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: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 {//from   www . j a va2 s  .  com
        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;
}