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:groovyx.net.http.HttpURLClient.java

/**
 * Perform a request.  Parameters are:// www .j  a  va 2 s.  co  m
 * <dl>
 *   <dt>url</dt><dd>the entire request URL</dd>
 *   <dt>path</dt><dd>the path portion of the request URL, if a default
 *     URL is set on this instance.</dd>
 *   <dt>query</dt><dd>URL query parameters for this request.</dd>
 *   <dt>timeout</dt><dd>see {@link HttpURLConnection#setReadTimeout(int)}</dd>
 *   <dt>method</dt><dd>This defaults to GET, or POST if a <code>body</code>
 *   parameter is also specified.</dd>
 *   <dt>contentType</dt><dd>Explicitly specify how to parse the response.
 *     If this value is ContentType.ANY, the response <code>Content-Type</code>
 *     header is used to determine how to parse the response.</dd>
 *   <dt>requestContentType</dt><dd>used in a PUT or POST request to
 *     transform the request body and set the proper
 *     <code>Content-Type</code> header.  This defaults to the
 *     <code>contentType</code> if unset.</dd>
 *   <dt>auth</dt><dd>Basic authorization; pass the value as a list in the
 *   form [user, pass]</dd>
 *   <dt>headers</dt><dd>additional request headers, as a map</dd>
 *   <dt>body</dt><dd>request content body, for a PUT or POST request.
 *     This will be encoded using the requestContentType</dd>
 * </dl>
 * @param args named parameters
 * @return the parsed response
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpResponseDecorator request(Map<String, ?> args)
        throws URISyntaxException, MalformedURLException, IOException {

    // copy so we don't modify the original collection when removing items:
    args = new HashMap<String, Object>(args);

    Object arg = args.remove("url");
    if (arg == null && this.defaultURL == null)
        throw new IllegalStateException("Either the 'defaultURL' property"
                + " must be set or a 'url' parameter must be passed to the " + "request method.");
    URIBuilder url = arg != null ? new URIBuilder(arg.toString()) : defaultURL.clone();

    arg = null;
    arg = args.remove("path");
    if (arg != null)
        url.setPath(arg.toString());
    arg = null;
    arg = args.remove("query");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'query' must be a map");
        url.setQuery((Map<?, ?>) arg);
    }

    HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection();
    conn.setInstanceFollowRedirects(this.followRedirects);

    arg = null;
    arg = args.remove("timeout");
    if (arg != null)
        conn.setConnectTimeout(Integer.parseInt(arg.toString()));

    arg = null;
    arg = args.remove("method");
    if (arg != null)
        conn.setRequestMethod(arg.toString());

    arg = null;
    arg = args.remove("contentType");
    Object contentType = arg != null ? arg : this.contentType;
    if (contentType instanceof ContentType)
        conn.addRequestProperty("Accept", ((ContentType) contentType).getAcceptHeader());

    arg = null;
    arg = args.remove("requestContentType");
    String requestContentType = arg != null ? arg.toString()
            : this.requestContentType != null ? this.requestContentType.toString()
                    : contentType != null ? contentType.toString() : null;

    // must add default headers before setting auth:
    for (String key : defaultHeaders.keySet())
        conn.addRequestProperty(key, defaultHeaders.get(key));

    arg = null;
    arg = args.remove("auth");
    if (arg != null) {
        if (oauth != null)
            log.warn("You are trying to use both OAuth and basic authentication!");
        try {
            List<?> vals = (List<?>) arg;
            conn.addRequestProperty("Authorization",
                    getBasicAuthHeader(vals.get(0).toString(), vals.get(1).toString()));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Auth argument must be a list in the form [user,pass]");
        }
    }

    arg = null;
    arg = args.remove("headers");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'headers' must be a map");
        Map<?, ?> headers = (Map<?, ?>) arg;
        for (Object key : headers.keySet())
            conn.addRequestProperty(key.toString(), headers.get(key).toString());
    }

    arg = null;
    arg = args.remove("body");
    if (arg != null) { // if there is a request POST or PUT body
        conn.setDoOutput(true);
        final HttpEntity body = (HttpEntity) encoderRegistry.getAt(requestContentType).call(arg);
        // TODO configurable request charset

        //TODO don't override if there is a 'content-type' in the headers list
        conn.addRequestProperty("Content-Type", requestContentType);
        try {
            // OAuth Sign if necessary.
            if (oauth != null)
                conn = oauth.sign(conn, body);
            // send request data
            DefaultGroovyMethods.leftShift(conn.getOutputStream(), body.getContent());
        } finally {
            conn.getOutputStream().close();
        }
    }
    // sign the request if we're using OAuth
    else if (oauth != null)
        conn = oauth.sign(conn, null);

    if (args.size() > 0) {
        String illegalArgs = "";
        for (String k : args.keySet())
            illegalArgs += k + ",";
        throw new IllegalArgumentException("Unknown named parameters: " + illegalArgs);
    }

    String method = conn.getRequestMethod();
    log.debug(method + " " + url);

    HttpResponse response = new HttpURLResponseAdapter(conn);
    if (ContentType.ANY.equals(contentType))
        contentType = conn.getContentType();

    Object result = this.getparsedResult(method, contentType, response);

    log.debug(response.getStatusLine());
    HttpResponseDecorator decoratedResponse = new HttpResponseDecorator(response, result);

    if (log.isTraceEnabled()) {
        for (Header h : decoratedResponse.getHeaders())
            log.trace(" << " + h.getName() + " : " + h.getValue());
    }

    if (conn.getResponseCode() > 399)
        throw new HttpResponseException(decoratedResponse);

    return decoratedResponse;
}

From source file:org.jboss.tools.ws.ui.utils.JAXRSTester.java

/**
 * Call a JAX-RS service// w  w  w . j a v a  2 s . c  o m
 * @param address
 * @param parameters
 * @param headers
 * @param methodType
 * @param requestBody
 * @param proxy
 * @param port
 * @throws Exception
 */
public void doTest(String address, Map<String, String> parameters, Map<String, String> headers,
        String methodType, String requestBody, String proxy, int port, String uid, String pwd)
        throws Exception {

    // handle the proxy
    Proxy proxyObject = null;
    if (proxy != null && proxy.length() > 0 && port > 0) {
        InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port);
        proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress);
    }

    // clear the returned results
    resultBody = EMPTY_STRING;

    // get the parms string
    String query = buildWebQuery(parameters);

    // Clear the address of any leading/trailing spaces
    address = address.trim();

    // build the complete URL
    URL url = null;
    if (query != null && query.trim().length() > 0) {
        // add the ? if there are parameters
        if (!address.endsWith("?") && !address.contains("?")) {//$NON-NLS-1$ //$NON-NLS-2$

            // if we're a "GET" - add the ? by default
            if (methodType.equalsIgnoreCase("GET")) { //$NON-NLS-1$
                address = address + "?"; //$NON-NLS-1$

                // if we're a PUT or POST, check if we have parms
                // and add the ? if we do
            } else if (methodType.equalsIgnoreCase("POST")//$NON-NLS-1$ 
                    || methodType.equalsIgnoreCase("PUT") //$NON-NLS-1$
                    || methodType.equalsIgnoreCase("DELETE")) { //$NON-NLS-1$
                if (query.trim().length() > 0) {
                    address = address + "?"; //$NON-NLS-1$
                }
            }
        } else if (address.contains("?")) { //$NON-NLS-1$
            address = address + "&"; //$NON-NLS-1$
        }
        // add parms to the url if we have some
        url = new URL(address + query);
    } else {
        url = new URL(address);
    }

    // make connection
    HttpURLConnection httpurlc = null;
    if (proxyObject == null) {
        httpurlc = (HttpURLConnection) url.openConnection();
    } else {
        // if have proxy, pass it along
        httpurlc = (HttpURLConnection) url.openConnection(proxyObject);
    }

    // since we are expecting output back, set to true
    httpurlc.setDoOutput(true);

    // not sure what this does - may be used for authentication?
    httpurlc.setAllowUserInteraction(false);

    // set whether this is a GET or POST
    httpurlc.setRequestMethod(methodType);

    // if we have headers to add
    if (headers != null && !headers.isEmpty()) {
        Iterator<?> iter = headers.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) iter.next();
            if (entry.getKey() != null && entry.getKey() instanceof String)
                httpurlc.addRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }

    // if we have basic authentication to add, add it!
    if (uid != null && pwd != null) {
        String authStr = uid + ':' + pwd;
        byte[] authEncByte = Base64.encodeBase64(authStr.getBytes());
        String authStringEnc = new String(authEncByte);
        httpurlc.addRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$//$NON-NLS-2$
    }

    requestHeaders = httpurlc.getRequestProperties();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // CONNECT!
    httpurlc.connect();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // If we are doing a POST and we have some request body to pass along, do it
    if (requestBody != null && (methodType.equalsIgnoreCase("POST") //$NON-NLS-1$
            || methodType.equalsIgnoreCase("PUT"))) { //$NON-NLS-1$
        requestBody = WSTestUtils.stripNLsFromXML(requestBody);
        OutputStreamWriter out = new OutputStreamWriter(httpurlc.getOutputStream());
        String stripped = stripCRLF(requestBody);
        out.write(stripped);
        out.close();
    }

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // if we have headers to pass to user, copy them
    if (httpurlc.getHeaderFields() != null) {
        resultHeaders = httpurlc.getHeaderFields();
    }

    // retrieve result and put string results into the response
    InputStream is = null;
    try {
        is = httpurlc.getInputStream();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");//$NON-NLS-1$
        }
        br.close();
        resultBody = sb.toString();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    } catch (IOException ie) {
        try {
            is = httpurlc.getErrorStream();

            // is possible that we're getting nothing back in the error stream
            if (is != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");//$NON-NLS-1$
                }
                br.close();
                resultBody = sb.toString();
            }
        } catch (IOException ie2) {
            resultBody = ie2.getLocalizedMessage();
        }
    }

    // as a last resort, if we still have nothing to report,
    // show an error message to the user
    if (resultBody == null || resultBody.trim().isEmpty()) {
        resultBody = JBossWSUIMessages.JAXRSRSTestView_Message_Unsuccessful_Test;
    }

    // disconnect explicitly (may not be necessary)
    httpurlc.disconnect();
}

From source file:org.alfresco.repo.web.scripts.activities.SiteActivitySystemTest.java

private String callInOutWeb(String urlString, String method, String ticket, String data, String contentType,
        String soapAction) throws MalformedURLException, URISyntaxException, IOException {
    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);/*from  ww w .  j  av  a 2s  .co m*/

    conn.setRequestProperty("Content-type", contentType);

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

    if (soapAction != null) {
        conn.setRequestProperty("SOAPAction", soapAction);
    }

    if (ticket != null) {
        // add Base64 encoded authorization header
        // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication
        conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes()));
    }

    String result = null;
    BufferedReader br = null;
    DataOutputStream wr = null;
    OutputStream os = null;
    InputStream is = null;

    try {
        os = conn.getOutputStream();
        wr = new DataOutputStream(os);
        wr.write(data.getBytes());
        wr.flush();
    } finally {
        if (wr != null) {
            wr.close();
        }
        ;
        if (os != null) {
            os.close();
        }
        ;
    }

    try {
        is = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));

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

        result = sb.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        ;
        if (is != null) {
            is.close();
        }
        ;
    }

    return result;
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request/*  ww  w.  j  ava2  s  .  c o  m*/
 * @param resp servlet response
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    URL url = getURL(req, req.getParameter("uri"));
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(true);
    con.setAllowUserInteraction(false);
    con.setUseCaches(false);

    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    // pass along all appropriate HTTP headers
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = (String) headerNames.nextElement();
        if (!unproxiedHeaders.contains(hname.toLowerCase())) {
            con.addRequestProperty(hname, req.getHeader(hname));
        }
    }
    con.connect();

    // read POST data from incoming request, write to outgoing request
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    // read result headers of POST, write to response
    Map<String, List<String>> headers = con.getHeaderFields();
    for (String key : headers.keySet()) {
        if (key != null) { // TODO: why is this check necessary!
            List<String> header = headers.get(key);
            if (header.size() > 0)
                resp.setHeader(key, header.get(0));
        }
    }

    // read result data of POST, write out to response
    in = new BufferedInputStream(con.getInputStream());
    out = new BufferedOutputStream(resp.getOutputStream());
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    con.disconnect();
}

From source file:iracing.webapi.IracingWebApi.java

private boolean forumLoginAndGetCookie() {
    try {//w w w  . j a  v  a 2 s  . c  o  m
        // Make a connect to the server
        URL url = new URL(FORUM_LOGIN_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.addRequestProperty(COOKIE, cookie);

        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);
        HttpURLConnection.setFollowRedirects(false);

        conn.connect();

        if (isMaintenancePage(conn))
            return false;

        String headerName;
        boolean containsCookie = false;
        for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase(SET_COOKIE)) {
                containsCookie = true;
                addToCookieMap(conn.getHeaderField(i));
            }
        }
        if (containsCookie)
            createCookieFromMap();

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

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testGzipCompressionWithGzipAccept() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET);
    urlConn.addRequestProperty(HttpHeaders.ACCEPT_ENCODING, "gzip");
    assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode());
    String contentEncoding = urlConn.getHeaderField(HttpHeaders.CONTENT_ENCODING);
    assertTrue("gzip".equalsIgnoreCase(contentEncoding));
    InputStream downStream = urlConn.getInputStream();
    assertTrue(IOUtils.toByteArray(downStream).length < IOUtils.toByteArray(
            Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").openStream()).length);
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testHeaderResponse() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/headerResponse", HttpMethod.GET);
    urlConn.addRequestProperty("name", "name1");

    assertEquals(200, urlConn.getResponseCode());
    assertEquals("name1", urlConn.getHeaderField("name"));
    urlConn.disconnect();//  ww  w.  j  av  a  2  s . co m
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testListHeaderParam() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/listHeaderParam", HttpMethod.GET);
    urlConn.addRequestProperty("name", "name1,name3,name2,name1");
    assertEquals(200, urlConn.getResponseCode());
    assertEquals("name1,name3,name2,name1", getContent(urlConn));
    urlConn.disconnect();/*from  w  w  w.j a v a2 s .  com*/
}

From source file:iracing.webapi.IracingWebApi.java

private String doGetRequest(boolean needForumCookie, String url, String userAgent)
        throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return null;
    }// w  w w.  j  a  va 2 s  .  c o  m
    if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return null;
    }
    String output = null;
    try {
        // Make a connection
        URL oUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) oUrl.openConnection();

        conn.addRequestProperty(COOKIE, cookie);

        // request to have the response gzipped (bringing a 3.5Mb response down to 175kb)
        conn.addRequestProperty("Accept-Encoding", "gzip");
        if (userAgent != null)
            conn.addRequestProperty("User-Agent", userAgent);

        //            conn.setDoInput(true);
        //            conn.setUseCaches(false);
        //            conn.setInstanceFollowRedirects(false);
        //            HttpURLConnection.setFollowRedirects(false);

        //        logger.debug("opening connection to " + url.getFile());
        conn.connect();

        if (isMaintenancePage(conn))
            return null;

        // 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()));
        }

        // Read the response
        output = getResponseText(conn);
        //            System.out.println(output);

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

From source file:org.opentestsystem.shared.test.interactioncontext.FastInteractionContext.java

public FastInteractionResponse buildResponse(String method, URL url, Map<String, List<String>> headers,
        Reader body, long timeout) throws IOException {

    URI uri = null;// ww w  .ja  v  a 2s . com
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        synchronized (this) {
            getActiveTimingRecord().fail(String.format("Invalid URL: %s", url.toString()), e);
        }
    }

    int iTimeout = (int) Math.min(Integer.MAX_VALUE, timeout);

    FastInteractionResponse response = null;
    HttpURLConnection connection = null;

    // This value is only used if an error causes things to fail before the connection is created.
    long t_start = System.currentTimeMillis();
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(iTimeout);
        connection.setReadTimeout(iTimeout);

        // Expect to send ouptut if a body has been supplied
        connection.setDoOutput(body != null);

        // Set headers (except cookies)
        if (headers != null) {
            for (Entry<String, List<String>> header_i : headers.entrySet()) {
                connection.setRequestProperty(header_i.getKey(), StringUtils.join(header_i.getValue(), ','));
            }
        } else {
            headers = new HashMap<String, List<String>>();
        }

        // Set cookies
        for (Entry<String, List<String>> header_i : _cookies.get(uri, headers).entrySet()) {
            for (String cookie_j : header_i.getValue()) {
                connection.addRequestProperty(header_i.getKey(), cookie_j);
            }
        }

        // Log the request, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Posted HTTP request:\r\n\r\n");
            msg.append(method).append("\r\n");
            msg.append(uri.toString()).append("\r\n");
            for (Entry<String, List<String>> header_i : connection.getRequestProperties().entrySet()) {
                for (String value_j : header_i.getValue())
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
            }
            msg.append("\r\n");

            if (body != null) {
                String bodyString = IOUtils.toString(body);
                IOUtils.closeQuietly(body);
                body = new StringReader(bodyString);
                msg.append(bodyString);
            }

            _logger.debug(msg.toString());
        }

        // Start timing
        // We update here because we don't really want to count time spent above.
        t_start = System.currentTimeMillis();

        // Send the request
        connection.connect();

        // Send the body
        if (body != null) {
            try (OutputStream os = connection.getOutputStream();) {
                IOUtils.copy(body, os, "UTF-8");
            } finally {
                IOUtils.closeQuietly(body);
            }
        }

        // Record the cookies
        // SB-547 workaround: multiple set-cookie headers are sent for the same
        // cookie. Process the last.
        Map<String, String> cookieMap = new HashMap<>();
        for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
            if (StringUtils.equals(header_i.getKey(), "Set-Cookie")) {
                for (String value_j : header_i.getValue()) {
                    for (String value_k : StringUtils.split(value_j, ',')) {
                        String[] cookieParts = StringUtils.split(value_k, "=", 2);
                        if (cookieParts.length > 0) {
                            String oldValue = cookieMap.get(cookieParts[0]);
                            if (oldValue == null || oldValue.length() < value_k.length()) {
                                cookieMap.put(cookieParts[0], value_k);
                            }
                        }
                    }
                }
            }
        }
        List<String> cookieValues = new ArrayList<>(cookieMap.values());
        Map<String, List<String>> cookieHeaders = new HashMap<>();
        cookieHeaders.put("Set-Cookie", cookieValues);
        _cookies.put(uri, cookieHeaders);

        // Retrieve the response
        InputStream is = connection.getInputStream();
        response = new FastInteractionResponse(this, is, connection, timeout, t_start + timeout);
        IOUtils.closeQuietly(is);
        connection.disconnect();

        // Stop timing
        long t_end = System.currentTimeMillis();
        synchronized (this) {
            InteractionTimingRecord timingRecord = getActiveTimingRecord();
            if (timingRecord != null) {
                timingRecord.accumulate("REMOTE_TIME", t_end - t_start);
                timingRecord.accumulate("N_REQ", 1);
            }
        }

        // Log the response, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Response from HTTP request:\r\n\r\n");
            msg.append(uri.toString()).append("\r\n\r\n");
            for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
                for (String value_j : header_i.getValue()) {
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
                }
            }
            msg.append("\r\n");
            String bodyString = response.getResponseBodyAsString();
            if (bodyString != null) {
                if (bodyString.length() <= 1024) {
                    msg.append(bodyString);
                } else {
                    msg.append(String.format("Body length %d. Showing first 1024 characters\r\n\r\n",
                            bodyString.length()));
                    msg.append(bodyString.subSequence(0, 1024));
                }
            }
            _logger.debug(msg.toString());
        }

        return response;
    } catch (IOException e) {
        synchronized (this) {
            failActiveInteraction(String.format("IO Error trying to fill request to %s", url.toString()), e);
            InputStream es = null;
            es = connection.getErrorStream();
            response = new FastInteractionResponse(this, es, connection, timeout, t_start + timeout);
            IOUtils.closeQuietly(es);
        }
    }
    return response;
}