Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:com.inter.trade.view.slideplayview.util.AbFileUtil.java

/**
 * ????./*from  ww w.java  2 s . c o  m*/
 * @param url ?
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (AbStrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return name;
}

From source file:com.android.sdklib.repository.legacy.remote.internal.DownloadCache.java

/**
 * Saves part of the HTTP Response to the info file.
 *///from  ww w  . j  a  v a  2s. c o  m
private void saveInfo(@NonNull String urlString, @NonNull HttpURLConnection connection, @NonNull File info)
        throws IOException {
    Properties props = new Properties();

    // we don't need the status code & URL right now.
    // Save it in case we want to have it later (e.g. to differentiate 200 and 404.)
    props.setProperty(KEY_URL, urlString);
    props.setProperty(KEY_STATUS_CODE, Integer.toString(connection.getResponseCode()));

    for (String name : INFO_HTTP_HEADERS) {
        String h = connection.getHeaderField(name);
        if (h != null) {
            props.setProperty(name, h);
        }
    }

    saveProperties(info, props, "## Meta data for SDK Manager cache. Do not modify.", mFileOp);
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

private void test302RedirectWithJetty(final String sendRedirectLocation, String expectedLocation,
        int httpsServerPortParameter) throws Exception {
    // SETUP/*from  w  ww.java2 s .  c om*/
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    filterConfig.addInitParameter(XForwardedFilter.HTTPS_SERVER_PORT_PARAMETER,
            String.valueOf(httpsServerPortParameter));
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    HttpServlet mockServlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        public void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect(sendRedirectLocation);
        }

    };
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        httpURLConnection.setInstanceFollowRedirects(false);
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE
        Assert.assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, httpURLConnection.getResponseCode());
        String actualLocation = httpURLConnection.getHeaderField("Location");
        assertEquals(expectedLocation, actualLocation);

    } finally {
        server.stop();
    }
}

From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java

protected OidcResource resolve(final HttpURLConnection conn) throws IOException {
    SslSetup.configureHttpsUrlConnection(conn);
    try (final InputStream istr = conn.getInputStream()) {
        final int statusCode = conn.getResponseCode();
        if (statusCode == 304) {
            return new OidcResource(statusCode);
        } else {/*from  ww  w . j a  va  2s  .c  o  m*/
            Certificate[] certs = new Certificate[0];
            if (conn instanceof HttpsURLConnection) {
                certs = ((HttpsURLConnection) conn).getServerCertificates();
            }
            final long contentLength = conn.getContentLengthLong();
            if (contentLength > MAX_LENGTH) {
                throw new IOException(conn.getURL() + " content exceeds maximum size, " + MAX_LENGTH);
            }
            final byte[] content = ByteStreams.toByteArray(new BoundedInputStream(istr, MAX_LENGTH + 1));
            if (content.length > MAX_LENGTH) {
                throw new IOException(conn.getURL() + " content exceeds maximum size, " + MAX_LENGTH);
            }
            return new OidcResource(statusCode, conn.getHeaderField(HttpHeaders.LAST_MODIFIED),
                    conn.getHeaderField(HttpHeaders.ETAG), certs, content);
        }
    }
}

From source file:org.jared.synodroid.ds.server.SynoServer.java

public StringBuffer download(String uriP, String requestP) throws Exception {
    HttpURLConnection con = null;
    try {/*from  www  .j a  v a  2 s  .  c om*/
        // Create the connection
        con = createConnection(uriP, requestP, "GET", true);
        // Add the parameters
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(requestP);
        // Send the request
        wr.flush();

        // Try to retrieve the session cookie
        String newCookie = con.getHeaderField("set-cookie");
        if (newCookie != null) {
            synchronized (this) {
                cookies = newCookie;
            }
            if (DEBUG)
                Log.v(Synodroid.DS_TAG, "Retreived cookies: " + cookies);
        }
        // Now read the reponse and build a string with it
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (OutOfMemoryError e) {
            sb = null;
        }

        br.close();
        return sb;
    }
    // Unexpected exception
    catch (Exception ex) {
        if (DEBUG)
            Log.e(Synodroid.DS_TAG, "Unexpected error", ex);
        throw ex;
    }
    // Finally close everything
    finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:org.sakaiproject.commons.tool.entityprovider.CommonsEntityProvider.java

@EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST)
public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String urlString = (String) params.get("url");

    if (StringUtils.isBlank(urlString)) {
        throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    }//from w  w  w . j  av a 2  s.c  o  m

    try {
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL url = new URL(urlString);
        URLConnection c = url.openConnection();

        if (c instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) c;
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            String contentEncoding = conn.getContentEncoding();
            String contentType = conn.getContentType();
            int responseCode = conn.getResponseCode();
            log.debug("Response code: {}", responseCode);

            int redirectCounter = 1;
            while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) {
                String newUri = conn.getHeaderField("Location");
                log.debug("{}. New URI: {}", responseCode, newUri);
                String cookies = conn.getHeaderField("Set-Cookie");
                url = new URL(newUri);
                c = url.openConnection();
                conn = (HttpURLConnection) c;
                conn.setInstanceFollowRedirects(false);
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setRequestProperty("Cookie", cookies);
                conn.connect();
                contentEncoding = conn.getContentEncoding();
                contentType = conn.getContentType();
                responseCode = conn.getResponseCode();
                log.debug("Redirect counter: {}", redirectCounter);
                log.debug("Response code: {}", responseCode);
                redirectCounter += 1;
            }

            if (contentType != null
                    && (contentType.startsWith("text/html") || contentType.startsWith("application/xhtml+xml")
                            || contentType.startsWith("application/xml"))) {
                String mimeType = contentType.split(";")[0].trim();
                log.debug("mimeType: {}", mimeType);
                log.debug("encoding: {}", contentEncoding);

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

                String line = null;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                }

                return new ActionReturn(contentEncoding, mimeType, outputStream);
            } else {
                log.debug("Invalid content type {}. Throwing bad request ...", contentType);
                throw new EntityException("Url content type not supported", "",
                        HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (MalformedURLException mue) {
        throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    } catch (IOException ioe) {
        throw new EntityException("Failed to download url contents", "",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Perform an HTTP GET request on a URL whose response is expected to
 * be a 3xx redirection, and return the target redirection URL.
 * //from   w w  w  .j a  va2 s.  c o m
 * @param source the URL to request (relative URLs will resolve
 *          against the {@link #getBaseUrl() base URL}).
 * @return the URL returned by the "Location" header of the
 *         redirection response.
 * @throws RestClientException if an exception occurs during
 *           processing, or the server returns a 4xx or 5xx error
 *           response (in which case the response JSON message will be
 *           available as a {@link JsonNode} in the exception), or if
 *           the response was not a 3xx redirection.
 */
public URL getRedirect(URL source) throws RestClientException {
    try {
        HttpURLConnection connection = (HttpURLConnection) source.openConnection();
        connection.setRequestMethod("GET");
        if (authorizationHeader != null) {
            connection.setRequestProperty("Authorization", authorizationHeader);
        }
        connection.setRequestProperty("Accept", "application/json");
        connection.setInstanceFollowRedirects(false);
        int responseCode = connection.getResponseCode();
        // make sure we read any response content
        readResponseOrError(connection, new TypeReference<JsonNode>() {
        }, false);
        if (responseCode >= 300 && responseCode < 400) {
            // it was a redirect
            String redirectUrl = connection.getHeaderField("Location");
            return new URL(redirectUrl);
        } else {
            throw new RestClientException("Expected redirect but got " + responseCode);
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String visitingUrl = buildUrl(resource.getName());
    try {/*from  w ww .  ja  va 2  s  .  co m*/
        List<String> visitedUrls = new ArrayList<String>();

        for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) {
            if (visitedUrls.contains(visitingUrl)) {
                throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl);
            }
            visitedUrls.add(visitingUrl);

            URL url = new URL(visitingUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(this.proxy);

            urlConnection.setRequestProperty("Accept-Encoding", "gzip");
            if (!useCache) {
                urlConnection.setRequestProperty("Pragma", "no-cache");
            }

            addHeaders(urlConnection);

            // TODO: handle all response codes
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN
                    || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName()));
            }
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                visitingUrl = urlConnection.getHeaderField("Location");
                continue;
            }

            InputStream is = urlConnection.getInputStream();
            String contentEncoding = urlConnection.getHeaderField("Content-Encoding");
            boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding);
            if (isGZipped) {
                is = new GZIPInputStream(is);
            }
            inputData.setInputStream(is);
            resource.setLastModified(urlConnection.getLastModified());
            resource.setContentLength(urlConnection.getContentLength());
            break;
        }
    } catch (MalformedURLException e) {
        throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new ResourceDoesNotExistException("Unable to locate resource in repository", e);
    } catch (IOException e) {
        StringBuilder message = new StringBuilder("Error transferring file: ");
        message.append(e.getMessage());
        message.append(" from " + visitingUrl);
        if (getProxyInfo() != null && getProxyInfo().getHost() != null) {
            message.append(" with proxyInfo ").append(getProxyInfo().toString());
        }
        throw new TransferFailedException(message.toString(), e);
    }
}

From source file:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java

protected void getRequest(HttpReadResult result) throws ConnectionException {
    String method = "getRequest; ";
    StringBuilder logBuilder = new StringBuilder(method);
    try {/*from  w w w .jav a  2  s  .  c  om*/
        OAuthConsumer consumer = getConsumer();
        logBuilder.append("URL='" + result.getUrl() + "';");
        HttpURLConnection conn;
        boolean redirected = false;
        boolean stop = false;
        do {
            conn = (HttpURLConnection) result.getUrlObj().openConnection();
            conn.setInstanceFollowRedirects(false);
            if (result.authenticate) {
                setAuthorization(conn, consumer, redirected);
            }
            conn.connect();
            result.setStatusCode(conn.getResponseCode());
            switch (result.getStatusCode()) {
            case OK:
                if (result.fileResult != null) {
                    HttpConnectionUtils.readStreamToFile(conn.getInputStream(), result.fileResult);
                } else {
                    result.strResponse = HttpConnectionUtils.readStreamToString(conn.getInputStream());
                }
                stop = true;
                break;
            case MOVED:
                redirected = true;
                result.setUrl(conn.getHeaderField("Location").replace("%3F", "?"));
                String logMsg3 = (result.redirected ? "Following redirect to " : "Not redirected to ") + "'"
                        + result.getUrl() + "'";
                logBuilder.append(logMsg3 + "; ");
                MyLog.v(this, method + logMsg3);
                if (MyLog.isLoggable(MyLog.APPTAG, MyLog.VERBOSE)) {
                    StringBuilder message = new StringBuilder(method + "Headers: ");
                    for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
                        for (String value : entry.getValue()) {
                            message.append(entry.getKey() + ": " + value + ";\n");
                        }
                    }
                    MyLog.v(this, message.toString());
                }
                conn.disconnect();
                break;
            default:
                result.strResponse = HttpConnectionUtils.readStreamToString(conn.getErrorStream());
                stop = result.fileResult == null || !result.authenticate;
                if (!stop) {
                    result.authenticate = false;
                    String logMsg4 = "Retrying without authentication connection to '" + result.getUrl() + "'";
                    logBuilder.append(logMsg4 + "; ");
                    MyLog.v(this, method + logMsg4);
                }
                break;
            }
        } while (!stop);
    } catch (ConnectionException e) {
        throw e;
    } catch (IOException e) {
        throw new ConnectionException(logBuilder.toString(), e);
    }
}

From source file:net.sparkeh.magisterlib.host.MagisterRequest.java

public void sendRequest(MagisterHost host) throws MalformedURLException, IOException {
    URL obj = new URL(host.getApiHost() + subUrl);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(reqOut.toString());
    con.setRequestProperty("User-Agent", userAgent);
    con.setRequestProperty("Content-Type", contentType);
    for (Entry<String, String> e : this.headersIn.entrySet()) {
        con.setRequestProperty(e.getKey(), e.getValue());
    }/*  w  w  w .  j  av  a  2 s. c  om*/
    if (reqOut != RequestType.GET && this.bodyOut.length() > 0) {
        con.setDoOutput(true);
        con.getOutputStream().write(this.bodyOut.getBytes("UTF-8"));
    }
    this.responseCodeIn = con.getResponseCode();
    System.out.println("\nSending '" + reqOut.toString() + "' request to URL : " + obj.getPath());
    System.out.println("Response Code : " + this.responseCodeIn);
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    this.headersIn.clear();
    for (String key : con.getHeaderFields().keySet()) {
        this.headersIn.put(key, con.getHeaderField(key));
    }
    this.bodyIn = response.toString();
}