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.autonavi.gxdtaojin.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());// www .  j a v a  2s . c  o  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 = null;
    try {
        parsedUrl = new URL(url);
    } catch (Throwable t) {
        t.printStackTrace();
        parsedUrl = new URL("http://www.google.com");
    }
    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.mome.main.netframe.volley.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 w w  .  j  a 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.farru.android.volley.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   www. 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:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from   ww w . j  ava2  s  . c o m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

void InitAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    String ref = null;/*from  w  w w.java2 s .  co m*/
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }
}

From source file:com.chen.cy.talkimage.network.xvolley.XHurlStack.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  w w.  jav  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) {
            //
            // ?????
            for (int i = 0; i < header.getValue().size(); i++) {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(i));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

@Override
@SuppressWarnings("deprecation")
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());//from ww  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);
    OkUrlFactory okFactory = new OkUrlFactory(mClient);
    HttpURLConnection connection = openOkHttpURLConnection(okFactory, 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.amazonaws.http.UrlHttpClient.java

@SuppressWarnings("checkstyle:emptyblock")
HttpResponse createHttpResponse(final HttpRequest request, final HttpURLConnection connection)
        throws IOException {
    // connection.setDoOutput(true);
    final String statusText = connection.getResponseMessage();
    final int statusCode = connection.getResponseCode();
    InputStream content = connection.getErrorStream();
    if (content == null) {
        // HEAD method doesn't have a body
        if (!"HEAD".equals(request.getMethod())) {
            try {
                content = connection.getInputStream();
            } catch (final IOException ioe) {
                // getInputStream() can throw an exception when there is no
                // input stream.
            }//from w  w w.j a v  a2  s.c  om
        }
    }

    final HttpResponse.Builder builder = HttpResponse.builder().statusCode(statusCode).statusText(statusText)
            .content(content);
    for (final Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        // skip null field that stores connection status
        if (header.getKey() == null) {
            continue;
        }
        // No AWS service return a list of header values, so it's safe to
        // take the first one.
        builder.header(header.getKey(), header.getValue().get(0));
    }

    return builder.build();
}

From source file:winterwell.jtwitter.URLConnectionHttpClient.java

private String processError2_reason(HttpURLConnection connection) throws IOException {
    // Try for a helpful message from Twitter
    InputStream es = connection.getErrorStream();
    String errorPage = null;//from w w w  .ja  v a  2s  .c  om
    if (es != null) {
        try {
            errorPage = read(es);
            // is it json?         
            JSONObject je = new JSONObject(errorPage);
            String error = je.getString("error");
            if (error != null && error.length() != 0) {
                return error;
            }
        } catch (Exception e) {
            // guess not!            
        }
    }
    // normal error channels
    String error = connection.getResponseMessage();
    Map<String, List<String>> headers = connection.getHeaderFields();
    List<String> errorMessage = headers.get(null);
    if (errorMessage != null && !errorMessage.isEmpty()) {
        error += "\n" + errorMessage.get(0);
    }
    if (errorPage != null && !errorPage.isEmpty()) {
        error += "\n" + errorPage;
    }
    return error;
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

/**
 * Open an inputStream to the HTML content at the given URL, making recursive calls for
 * redirection (HTTP 301, 302)./*www .  j a v a  2  s  .co  m*/
 *
 * @param url            The URL to open a stream to
 * @param logWriter      A PrintWriter to log debug info to. Can be null
 * @param recursionLevel The redirect recursion level. Starts at 0, doesn't go past 10
 * @return An InputStream to the content at the URL, or null
 * @throws IOException Thrown if something goes terribly wrong
 */
private static @Nullable InputStream getHttpInputStream(URL url, @Nullable PrintWriter logWriter,
        int recursionLevel) throws IOException {

    /* Don't allow infinite recursion */
    if (recursionLevel > 10) {
        return null;
    }

    /* Make the URL & connection objects, follow redirects, timeout after 5s */
    HttpURLConnection.setFollowRedirects(true);
    HttpURLConnection connection = (HttpURLConnection) (url).openConnection();
    connection.setConnectTimeout(5000);
    connection.setInstanceFollowRedirects(true);

    /* If the connection is not OK, debug print the response */
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        /* Log the URL and response code */
        if (logWriter != null) {
            logWriter.write("URL : " + url.toString() + '\n');
            logWriter.write("RESP: " + connection.getResponseCode() + '\n');
        }

        /* Comb through header fields for a redirect location */
        URL nextUrl = null;
        for (String key : connection.getHeaderFields().keySet()) {
            /* Log the header */
            if (logWriter != null) {
                logWriter.write("HDR : [" + key + "] " + connection.getHeaderField(key) + '\n');
            }

            /* Found the URL to try next */
            if (key != null && key.equalsIgnoreCase("location")) {
                nextUrl = new URL(connection.getHeaderField(key));
            }
        }

        /* If the next location is still null, comb through the HTML
         * This is kind of a hack for when sites.google.com is serving up malformed 302
         * redirects and all the header fields end up being in this input stream
         */
        if (nextUrl == null) {
            /* Open the stream */
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            int linesRead = 0;
            /* Read one line at a time */
            while ((line = br.readLine()) != null) {
                /* Log the line */
                if (logWriter != null) {
                    logWriter.write("HTML:" + line + '\n');
                }
                /* Check for a location */
                if (line.toLowerCase().contains("location")) {
                    nextUrl = new URL(line.split("\\s+")[1]);
                    break;
                }
                /* Count the line, make sure to quit after 1000 */
                linesRead++;
                if (linesRead > 1000) {
                    break;
                }
            }
        }

        if (nextUrl != null) {
            /* If there is a URL to follow, follow it */
            return getHttpInputStream(nextUrl, logWriter, recursionLevel + 1);
        } else {
            /* Otherwise return null */
            return null;
        }

    } else {
        /* HTTP response is A-OK. Return the inputStream */
        return connection.getInputStream();
    }
}