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:net.ymate.module.webproxy.WebProxy.java

private String __doParseContentBody(HttpURLConnection _conn, byte[] _content, String charset) throws Exception {
    if (StringUtils.contains(_conn.getHeaderField("Content-Encoding"), "gzip")) {
        ByteArrayInputStream _input = null;
        GZIPInputStream _gzip = null;
        ByteArrayOutputStream _output = null;
        try {/*from   w ww.  j  a v  a 2s  . c o m*/
            _input = new ByteArrayInputStream(_content);
            _gzip = new GZIPInputStream(_input);
            _output = new ByteArrayOutputStream();
            //
            IOUtils.copyLarge(_gzip, _output);
            return new String(_output.toByteArray(), charset);
        } finally {
            IOUtils.closeQuietly(_output);
            IOUtils.closeQuietly(_gzip);
            IOUtils.closeQuietly(_input);
        }
    }
    return new String(_content, charset);
}

From source file:org.mojohaus.plugins.site.MojohausPluginsMacro.java

private String getFinalUrl(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.connect();//www.  j a  v a  2s  .c  o m
    conn.getInputStream();
    if (conn.getResponseCode() == 301 || conn.getResponseCode() == 302) {
        String redirectUrl = conn.getHeaderField("Location");
        return getFinalUrl(redirectUrl);
    }
    return url;
}

From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Gets the file size of the specified resource from the HTTP header field "content-length"
 * @param url                     URL of the specified resource.
 * @return                        content-length, null otherwise.
 *//*w  ww .  j  av a  2  s.  com*/
public String getContentLength(String url) {
    String contentLength = null;
    try {
        String requestURL = url;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        URL httpURL = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        contentLength = connection.getHeaderField("content-length");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    TapjoyLog.i(TAPJOY_URL_CONNECTION, "content-length: " + contentLength);

    return contentLength;
}

From source file:org.apache.olingo.fit.tecsvc.http.ODataVersionConformanceITCase.java

@Test
public void validODataMaxVersionHeader() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "5.0");
    connection.connect();/*from ww  w.  ja  v a  2  s. co m*/

    assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));

    final String content = IOUtils.toString(connection.getErrorStream());
    assertNotNull(content);
}

From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java

public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception {
    URL url = new URL(channel.getEndpointReference().getAddress());
    log.debug("Opening connection to " + url + " using " + URLConnection.class.getName());
    try {/*from   ww  w .j  a v  a2  s .c  om*/
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", contentType.toString());
        if (contentType.getBaseType().equals("text/xml")) {
            connection.setRequestProperty("SOAPAction", "");
        }
        OutputStream out = connection.getOutputStream();
        out.write(message);
        out.close();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            log.debug("Response code: " + httpConnection.getResponseCode());
            log.debug("Response message: " + httpConnection.getResponseMessage());
            int i = 0;
            String headerValue;
            while ((headerValue = httpConnection.getHeaderField(i)) != null) {
                String headerName = httpConnection.getHeaderFieldKey(i);
                if (headerName != null) {
                    log.debug(headerName + ": " + headerValue);
                } else {
                    log.debug(headerValue);
                }
                i++;
            }
        }
        InputStream in = connection.getInputStream();
        IOUtils.copy(in, System.out);
        in.close();
    } catch (IOException ex) {
        log.debug("Got exception", ex);
        throw ex;
    }
}

From source file:org.wise.portal.presentation.web.controllers.teacher.project.AnalyzeProjectController.java

/**
 * Get the redirect location for the URL
 * @param urlString the url as a string//from  w ww. ja  va  2 s.  c  om
 * @return the redirect location
 * @throws MalformedURLException
 * @throws IOException
 */
private static String getRedirectLocation(String urlString) throws MalformedURLException, IOException {
    //create the URL object
    URL url = new URL(urlString);

    //create a connection to the url
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.connect();

    //get the redirect location
    String redirectLocation = conn.getHeaderField("Location");

    return redirectLocation;
}

From source file:Main.java

public Main() {
    JPanel inputPanel = new JPanel(new BorderLayout(3, 3));
    go.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                URL pageURL = new URL("http://www.google.com");
                HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection();
                int respCode = urlConnection.getResponseCode();
                String response = urlConnection.getResponseMessage();
                codeArea.setText("HTTP/1.x " + respCode + " " + response + "\n");
                int count = 1;
                while (true) {
                    String header = urlConnection.getHeaderField(count);
                    String key = urlConnection.getHeaderFieldKey(count);
                    if (header == null || key == null) {
                        break;
                    }/* w w  w . j a  v  a2  s.com*/
                    codeArea.append(urlConnection.getHeaderFieldKey(count) + ": " + header + "\n");
                    count++;
                }
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                Reader r = new InputStreamReader(in);
                int c;
                while ((c = r.read()) != -1) {
                    codeArea.append(String.valueOf((char) c));
                }
                codeArea.setCaretPosition(1);
            } catch (Exception ee) {
            }
        }
    });
    inputPanel.add(BorderLayout.EAST, go);
    JScrollPane codeScroller = new JScrollPane(codeArea);
    add(BorderLayout.NORTH, inputPanel);
    add(BorderLayout.CENTER, codeScroller);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700, 500);
    this.setVisible(true);
}

From source file:org.apache.olingo.fit.tecsvc.http.BasicHttpITCase.java

@Test
public void testFormat() throws Exception {
    URL url = new URL(SERVICE_URI + "?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.connect();/*from w  w  w . j a  v  a  2 s.c o m*/

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));
}

From source file:com.google.gdocsfs.GoogleDocs.java

public final int getContentLength(URL source) throws IOException {
    HttpURLConnection connection = null;
    try {/*ww w .jav a 2s. c o m*/
        connection = getConnection(source, "HEAD");
        connection.connect();

        { // get content length
            int contentLength = -1;
            String contentLengthStr = connection.getHeaderField("Content-Length");
            if (contentLengthStr != null) {
                try {
                    contentLength = Integer.parseInt(contentLengthStr);
                } catch (NumberFormatException e) {
                    log.warn("Can't parse the content lenght.", e);
                }
            }
            return contentLength;
        }

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void download(String url, File destination) {
    if (destination.exists() && !destination.delete()) {
        log.log(Level.INFO, "Unable to clean up existing file {0} before downloading", destination);
        return;//from w  ww  . j ava2  s . c  o  m
    }

    int attempts = 0;
    while (attempts++ < 5) {
        InputStream inputStream = null;

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            String length = connection.getHeaderField("Content-Length");
            if (length == null) {
                log.log(Level.INFO, "Download attempt {0} failed", attempts);
                Thread.sleep(500);
                continue;
            }

            long len = Long.parseLong(length);
            if (len <= 0) {
                log.log(Level.INFO, "Download attempt {0} failed", attempts);
                Thread.sleep(500);
                continue;
            }

            inputStream = connection.getInputStream();
            copyFile(inputStream, destination, SharedLocale.tr("runtimeFetcher.download"), len);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Closer.close(inputStream);
        }
    }
}