Example usage for java.net HttpURLConnection getHeaderFields

List of usage examples for java.net HttpURLConnection getHeaderFields

Introduction

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

Prototype

public Map<String, List<String>> getHeaderFields() 

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

From source file:com.baasbox.android.HttpUrlConnectionClient.java

@Override
public HttpResponse execute(HttpRequest request) throws BaasException {
    try {/* ww w .  j  a v a 2  s .  c om*/
        HttpURLConnection connection = openConnection(request.url);

        for (String name : request.headers.keySet()) {
            connection.addRequestProperty(name, request.headers.get(name));
        }
        setupConnectionForRequest(connection, request);
        connection.connect();

        int responseCode = -1;
        try {
            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            responseCode = connection.getResponseCode();
        }
        Logger.info("Connection response received");
        if (responseCode == -1) {
            throw new IOException("Connection failed");
        }
        StatusLine line = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseCode,
                connection.getResponseMessage());
        BasicHttpResponse response = new BasicHttpResponse(line);
        response.setEntity(asEntity(connection));
        for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
            if (header.getKey() != null) {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
        return response;
    } catch (IOException e) {
        throw new BaasIOException(e);
    }
}

From source file:org.broad.igv.util.HttpUtils.java

private void logHeaders(HttpURLConnection conn) {
    Map<String, List<String>> headerFields = conn.getHeaderFields();
    log.debug("Headers for " + conn.getURL());
    for (Map.Entry<String, List<String>> header : headerFields.entrySet()) {
        log.debug(header.getKey() + ": " + org.apache.commons.lang.StringUtils.join(header.getValue(), ','));
    }//www. j a v a  2 s .c  o m
}

From source file:com.vincestyling.netroid.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//from  w  ww .  j  a v a  2  s. c o m
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:org.apache.slider.core.restclient.UrlConnectionOperations.java

public HttpOperationResponse execHttpOperation(HttpVerb verb, URL url, byte[] payload, String contentType)
        throws IOException, AuthenticationException {
    HttpURLConnection conn = null;
    HttpOperationResponse outcome = new HttpOperationResponse();
    int resultCode;
    byte[] body = null;
    log.debug("{} {} spnego={}", verb, url, useSpnego);

    boolean doOutput = verb.hasUploadBody();
    if (doOutput) {
        Preconditions.checkArgument(payload != null, "Null payload on a verb which expects one");
    }//from  ww w. j  ava2s  . c  o  m
    try {
        conn = openConnection(url);
        conn.setRequestMethod(verb.getVerb());
        conn.setDoOutput(doOutput);
        if (doOutput) {
            conn.setRequestProperty("Content-Type", contentType);
        }

        // now do the connection
        conn.connect();

        if (doOutput) {
            OutputStream output = conn.getOutputStream();
            IOUtils.write(payload, output);
            output.close();
        }

        resultCode = conn.getResponseCode();
        outcome.lastModified = conn.getLastModified();
        outcome.contentType = conn.getContentType();
        outcome.headers = conn.getHeaderFields();
        InputStream stream = conn.getErrorStream();
        if (stream == null) {
            stream = conn.getInputStream();
        }
        if (stream != null) {
            // read into a buffer.
            body = IOUtils.toByteArray(stream);
        } else {
            // no body: 
            log.debug("No body in response");

        }
    } catch (SSLException e) {
        throw e;
    } catch (IOException e) {
        throw NetUtils.wrapException(url.toString(), url.getPort(), "localhost", 0, e);

    } catch (AuthenticationException e) {
        throw new AuthenticationException("From " + url + ": " + e, e);

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    uprateFaults(HttpVerb.GET, url.toString(), resultCode, "", body);
    outcome.responseCode = resultCode;
    outcome.data = body;
    return outcome;
}

From source file:org.overlord.gadgets.web.server.servlets.RestProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  w  w.j  av a  2 s  .  c o  m
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Proxy inbound endpoint: " + req.getRequestURI());
    // Connect to proxy URL.
    String urlStr = getProxyUrl(req);
    String queryString = req.getQueryString();
    if (queryString != null) {
        urlStr = urlStr + "?" + queryString;
    }
    System.out.println("Proxying to: " + urlStr);
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    // Proxy all of the request headers.
    Enumeration<?> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = String.valueOf(headerNames.nextElement());
        Enumeration<?> headerValues = req.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            String headerValue = String.valueOf(headerValues.nextElement());
            conn.addRequestProperty(headerName, headerValue);
        }
    }

    // Handle authentication
    RestProxyAuthProvider authProvider = getAuthProvider();
    if (authProvider != null) {
        authProvider.provideAuthentication(conn);
    }

    // Now connect and proxy the response.
    InputStream proxyUrlResponseStream = null;
    try {
        proxyUrlResponseStream = conn.getInputStream();
        resp.setStatus(conn.getResponseCode());
        // Proxy the response headers
        for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
            String respHeaderName = entry.getKey();
            if (respHeaderName != null && !respHeaderName.equalsIgnoreCase("transfer-encoding")) {
                for (String respHeaderValue : entry.getValue()) {
                    resp.addHeader(respHeaderName, respHeaderValue);
                }
            }
        }

        // Proxy the response body.
        IOUtils.copy(proxyUrlResponseStream, resp.getOutputStream());
    } finally {
        IOUtils.closeQuietly(proxyUrlResponseStream);
        conn.disconnect();
    }
}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Read an error response from the given connection and throw a
 * suitable {@link RestClientException}. This method always throws an
 * exception, it will never return normally.
 */// ww  w . j  a  va 2 s  .c om
private void readError(HttpURLConnection connection) throws RestClientException {
    InputStream stream;
    try {
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getErrorStream());
        } else {
            stream = connection.getErrorStream();
        }

        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");

        try {
            JsonNode errorNode = null;
            errorNode = MAPPER.readTree(stream);

            throw new RestClientException("Server returned response code " + connection.getResponseCode(),
                    errorNode, connection.getResponseCode(), connection.getHeaderFields());

        } finally {
            reader.close();
        }
    } catch (RestClientException e2) {
        throw e2;
    } catch (Exception e2) {
        throw new RestClientException("Error communicating with server", e2);
    }
}

From source file:com.zjut.material_wecenter.Client.java

/**
 * doPost ??POST/*from   ww  w . j  a v a 2  s  .c  om*/
 * @param URL URL
 * @param params ?
 * @return ?NULL
 */
private String doPost(String URL, Map<String, String> params) {
    // 
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // ?
    try {
        URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // ??
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // ?
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // ?Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // ??
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            return new String(byteArrayOutputStream.toByteArray());
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}

From source file:com.ab.network.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from   w ww .ja  va 2 s  . com
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java

private HttpResponse performNormalREquest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from  w  ww.  j av  a2s  .c om
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:neal.http.impl.httpstack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, HttpErrorCollection.AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*  w  w  w  . j  a  v a  2s  . co m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}