Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

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

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:org.apache.openaz.xacml.admin.util.RESTfulPAPEngine.java

/**
 * Send a request to the PAP Servlet and get the response.
 * //from   w  w  w  .  j  a  v  a2  s. c  o m
 * The content is either an InputStream to be copied to the Request OutputStream
 *    OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
 * 
 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
 * 
 * @param method
 * @param content   - EITHER an InputStream OR an Object to be encoded in JSON
 * @param collectionTypeClass
 * @param responseContentClass
 * @param parameters
 * @return
 * @throws Exception
 */
private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
        String... parameters) throws PAPException {
    HttpURLConnection connection = null;
    try {
        String fullURL = papServletURLString;
        if (parameters != null && parameters.length > 0) {
            String queryString = "";
            for (String p : parameters) {
                queryString += "&" + p;
            }
            fullURL += "?" + queryString.substring(1);
        }

        // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
        if (method.equals("GET") && content instanceof PDP && responseContentClass == StdPDPStatus.class) {
            // Adjust the url and properties appropriately
            fullURL = ((PDP) content).getId() + "?type=Status";
            content = null;
        }

        URL url = new URL(fullURL);

        //
        // Open up the connection
        //
        connection = (HttpURLConnection) url.openConnection();
        //
        // Setup our method and headers
        //
        connection.setRequestMethod(method);
        //            connection.setRequestProperty("Accept", "text/x-java-properties");
        //               connection.setRequestProperty("Content-Type", "text/x-java-properties");
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        if (content != null) {
            if (content instanceof InputStream) {
                try {
                    //
                    // Send our current policy configuration
                    //
                    try (OutputStream os = connection.getOutputStream()) {
                        int count = IOUtils.copy((InputStream) content, os);
                        if (logger.isDebugEnabled()) {
                            logger.debug("copied to output, bytes=" + count);
                        }
                    }
                } catch (Exception e) {
                    logger.error("Failed to write content in '" + method + "'", e);
                    throw e;
                }
            } else {
                // The content is an object to be encoded in JSON
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(connection.getOutputStream(), content);
            }
        }
        //
        // Do the connect
        //
        connection.connect();
        if (connection.getResponseCode() == 204) {
            logger.info("Success - no content.");
            return null;
        } else if (connection.getResponseCode() == 200) {
            logger.info("Success. We have a return object.");

            // get the response content into a String
            String json = null;
            // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
            java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
            scanner.useDelimiter("\\A");
            json = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
            logger.info("JSON response from PAP: " + json);

            // convert Object sent as JSON into local object
            ObjectMapper mapper = new ObjectMapper();

            if (collectionTypeClass != null) {
                // collection of objects expected
                final CollectionType javaType = mapper.getTypeFactory()
                        .constructCollectionType(collectionTypeClass, responseContentClass);

                Object objectFromJSON = mapper.readValue(json, javaType);
                return objectFromJSON;
            } else {
                // single value object expected
                Object objectFromJSON = mapper.readValue(json, responseContentClass);
                return objectFromJSON;
            }

        } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
            // redirection
            String newURL = connection.getHeaderField("Location");
            if (newURL == null) {
                logger.error(
                        "No Location header to redirect to when response code=" + connection.getResponseCode());
                throw new IOException(
                        "No redirect Location header when response code=" + connection.getResponseCode());
            }
            int qIndex = newURL.indexOf("?");
            if (qIndex > 0) {
                newURL = newURL.substring(0, qIndex);
            }
            logger.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
            return newURL;
        } else {
            logger.warn("Unexpected response code: " + connection.getResponseCode() + "  message: "
                    + connection.getResponseMessage());
            throw new IOException("Server Response: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage());
        }

    } catch (Exception e) {
        logger.error("HTTP Request/Response to PAP: " + e, e);
        throw new PAPException("Request/Response threw :" + e);
    } finally {
        // cleanup the connection
        if (connection != null) {
            try {
                // For some reason trying to get the inputStream from the connection
                // throws an exception rather than returning null when the InputStream does not exist.
                InputStream is = null;
                try {
                    is = connection.getInputStream();
                } catch (Exception e1) { //NOPMD
                    // ignore this
                }
                if (is != null) {
                    is.close();
                }

            } catch (IOException ex) {
                logger.error("Failed to close connection: " + ex, ex);
            }
            connection.disconnect();
        }
    }
}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;/*w ww  . j a va 2 s.  c  om*/

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue());

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:com.techventus.server.voice.Voice.java

/**
 * HTTP GET request for a given URL String.
 * //from w w w . j  a v  a 2 s . com
 * @param urlString
 *            the url string
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
String get(String urlString) throws IOException {
    URL url = new URL(urlString);
    //+ "?auth=" + URLEncoder.encode(authToken, enc));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);
    conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(urlString + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
            || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
            || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) {
        redirectCounter++;
        if (redirectCounter > MAX_REDIRECTS) {
            redirectCounter = 0;
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Too manny redirects. exiting.");
        }
        String location = conn.getHeaderField("Location");
        if (location != null && !location.equals("")) {
            System.out.println(urlString + " - " + responseCode + " - new URL: " + location);
            return get(location);
        } else {
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Received moved answer but no Location. exiting.");
        }
    } else {
        is = conn.getErrorStream();
    }
    redirectCounter = 0;

    if (is == null) {
        throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                + ") : InputStream was null : exiting.");
    }

    String result = "";
    try {
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line + "\n\r");
        }
        rd.close();
        result = sb.toString();
    } catch (Exception e) {
        throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - "
                + e.getLocalizedMessage());
    }
    return result;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Write REST request to {@link HttpURLConnection}.
 * //w  w w  .  j  a va2 s  . c  o m
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (POST, PUT)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param fileName String File name of the attachment to set as binary content.
 * @return {@link HttpURLConnection} object.
 * @throws IOException
 */
private HttpURLConnection writeRequest(String endPoint, String httpMethod, byte responseType,
        Map<String, String> headersMap, String fileName, boolean isBinaryContent) throws IOException {

    OutputStream output = null;

    URL url = new URL(endPoint);
    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    // Disable automatic redirects
    httpConnection.setInstanceFollowRedirects(false);
    httpConnection.setRequestMethod(httpMethod);

    //Create byte array to send binary attachment
    FileInputStream fileInputStream = null;
    File file = new File(pathToResourcesDirectory, fileName);
    byte[] byteArray = new byte[(int) file.length()];
    fileInputStream = new FileInputStream(file);
    fileInputStream.read(byteArray);
    fileInputStream.close();

    for (String key : headersMap.keySet()) {
        httpConnection.setRequestProperty(key, headersMap.get(key));
    }

    if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) {
        httpConnection.setDoOutput(true);
        try {

            output = httpConnection.getOutputStream();
            output.write(byteArray);

        } finally {

            if (output != null) {
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    log.error("Error while closing the connection");
                }
            }

        }
    }

    return httpConnection;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Write REST request to {@link HttpURLConnection}.
 * /*from w  ww.jav a 2 s  .  c o  m*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return {@link HttpURLConnection} object.
 * @throws IOException
 */
private HttpURLConnection writeRequest(String endPoint, String httpMethod, byte responseType,
        Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap)
        throws IOException {

    String requestData = "";

    if (requestFileName != null && !requestFileName.isEmpty()) {

        requestData = loadRequestFromFile(requestFileName, parametersMap);

    } else if (responseType == RestResponse.JSON_TYPE) {
        requestData = "{}";
    }
    OutputStream output = null;

    URL url = new URL(endPoint);
    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    // Disable automatic redirects
    httpConnection.setInstanceFollowRedirects(false);
    httpConnection.setRequestMethod(httpMethod);

    for (String key : headersMap.keySet()) {
        httpConnection.setRequestProperty(key, headersMap.get(key));
    }

    if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) {
        httpConnection.setDoOutput(true);
        try {

            output = httpConnection.getOutputStream();
            output.write(requestData.getBytes(Charset.defaultCharset()));

        } finally {

            if (output != null) {
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    log.error("Error while closing the connection");
                }
            }

        }
    }

    return httpConnection;
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make tokenrequest.//  w ww.ja  v  a  2s.c  o m
 *
 * @param tokenurl
 *            the tokenurl
 * @param urlParameters
 *            the url parameters
 * @param authheader
 *            the authheader
 * @return the string
 */
protected String makeTokenrequest(String tokenurl, String urlParameters, String authheader,
        MessageContext messageContext) {

    ICallresponse icallresponse = null;
    String retStr = "";

    URL neturl;
    HttpURLConnection connection = null;

    log.info("url : " + tokenurl + " | urlParameters : " + urlParameters + " | authheader : " + authheader
            + " Request ID: " + UID.getRequestID(messageContext));

    if ((tokenurl != null && tokenurl.length() > 0) && (urlParameters != null && urlParameters.length() > 0)
            && (authheader != null && authheader.length() > 0)) {
        try {

            byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
            int postDataLength = postData.length;
            URL url = new URL(tokenurl);

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", authheader);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
            connection.setUseCaches(false);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postData);
            wr.flush();
            wr.close();

            if ((connection.getResponseCode() != 200) && (connection.getResponseCode() != 201)
                    && (connection.getResponseCode() != 400) && (connection.getResponseCode() != 401)) {
                log.info("connection.getResponseMessage() : " + connection.getResponseMessage());
                throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
            }

            InputStream is = null;
            if ((connection.getResponseCode() == 200) || (connection.getResponseCode() == 201)) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String output;
            while ((output = br.readLine()) != null) {
                retStr += output;
            }
            br.close();
        } catch (Exception e) {
            log.error("[WSRequestService ], makerequest, " + e.getMessage(), e);
            return null;
        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    } else {
        log.error("Token refresh details are invalid.");
    }

    return retStr;
}

From source file:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;// w w  w . j av  a  2  s .  c o m

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    Object o = null;

    if (progress != null) {
        o = progress.get();
    }

    Progress p = null;

    if (o != null) {
        p = new Progress(o);
    }

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue(), p);

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:org.pixmob.httpclient.HttpRequestBuilder.java

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {//from   w  ww  .ja v a 2 s  . c om
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }

            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
                        .append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }

            if (!contentSet
                    && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }

        // It seems that when writing content starts the connection
        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {

            if (content == null) {
                noContent();
            }

            conn.setDoOutput(true);
            if (!contentSet) {
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
            } else if (contentType != null) {
                conn.setRequestProperty("Content-Type", contentType);
            }
            conn.setFixedLengthStreamingMode(content.length);

            final OutputStream out = conn.getOutputStream();
            out.write(content);
            out.flush();
        }

        conn.connect();

        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {//from  w w  w .j a  va  2 s  .co  m
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }

            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
                        .append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }

            if (!contentSet
                    && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {
            if (content != null) {
                conn.setDoOutput(true);
                if (!contentSet) {
                    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
                } else if (contentType != null) {
                    conn.setRequestProperty("Content-Type", contentType);
                }
                conn.setFixedLengthStreamingMode(content.length);

                final OutputStream out = conn.getOutputStream();
                out.write(content);
                out.flush();
            } else {
                conn.setFixedLengthStreamingMode(0);
            }
        }

        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }

        conn.connect();

        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                e.printStackTrace();
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}