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.amastigote.xdu.query.module.EduSystem.java

private void preLogin() throws IOException {
    URL url = new URL(SYS_HOST);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.connect();//from  w w w  .  j  a v a2s. c  o m
    List<String> cookies_to_set_a = httpURLConnection.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set_a)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(e.indexOf("JSESSIONID=") + 11, e.indexOf(";"));
    httpURLConnection.disconnect();

    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(true);
    httpURLConnection.connect();

    List<String> cookies_to_set = httpURLConnection.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set) {
        if (e.contains("route="))
            ROUTE = e.substring(6);
        else if (e.contains("JSESSIONID="))
            LOGIN_JSESSIONID = e.substring(11, e.indexOf(";"));
        else if (e.contains("BIGipServeridsnew.xidian.edu.cn="))
            BIGIP_SERVER_IDS_NEW = e.substring(32, e.indexOf(";"));
    }

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("input[type=hidden]");

    for (Element element : elements) {
        switch (element.attr("name")) {
        case "lt":
            LOGIN_PARAM_lt = element.attr("value");
            break;
        case "execution":
            LOGIN_PARAM_execution = element.attr("value");
            break;
        case "_eventId":
            LOGIN_PARAM__eventId = element.attr("value");
            break;
        case "rmShown":
            LOGIN_PARAM_rmShown = element.attr("value");
            break;
        }
    }
}

From source file:com.hpe.application.automation.tools.common.rest.RestClient.java

/**
 * @param connection/*from ww  w.  j  a v a2  s  .c  om*/
 *            that is already connected to its url with an http request, and that should contain
 *            a response for us to retrieve
 * @return a response from the server to the previously submitted http request
 */
private Response retrieveHtmlResponse(HttpURLConnection connection) {

    Response ret = new Response();

    try {
        ret.setStatusCode(connection.getResponseCode());
        ret.setHeaders(connection.getHeaderFields());
    } catch (Exception cause) {
        throw new SSEException(cause);
    }

    InputStream inputStream;
    // select the source of the input bytes, first try 'regular' input
    try {
        inputStream = connection.getInputStream();
    }
    // if the connection to the server somehow failed, for example 404 or 500,
    // con.getInputStream() will throw an exception, which we'll keep.
    // we'll also store the body of the exception page, in the response data. */
    catch (Exception e) {
        inputStream = connection.getErrorStream();
        ret.setFailure(e);
    }

    // this takes data from the previously set stream (error or input)
    // and stores it in a byte[] inside the response
    ByteArrayOutputStream container = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int read;
    try {
        while ((read = inputStream.read(buf, 0, 1024)) > 0) {
            container.write(buf, 0, read);
        }
        ret.setData(container.toByteArray());
    } catch (Exception ex) {
        throw new SSEException(ex);
    }

    return ret;
}

From source file:winterwell.jtwitter.URLConnectionHttpClient.java

/**
 * Cache headers for {@link #getHeader(String)}
 * /*w  ww .  j ava2  s.  c  o  m*/
 * @param connection
 */
protected final void processHeaders(HttpURLConnection connection) {
    headers = connection.getHeaderFields();
    updateRateLimits();
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

@Test
public void testGet() throws Exception {
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", new HttpUrlConnectionProvider(connection));

    doReturn(HttpStatus.SC_OK).when(connection).getResponseCode();
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(RESPONSE_DATA));
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);

    HeaderAndBody result = provider.get();
    assertArrayEquals(RESPONSE_DATA, result.getBody());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));

}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean login(String username, String password) throws IOException {
    preLogin();/*from  ww w .  j a v  a2s  .c o m*/
    URL url = new URL(LOGIN_HOST + LOGIN_SUFFIX);
    HttpURLConnection httpURLConnection_a = (HttpURLConnection) url.openConnection();
    httpURLConnection_a.setRequestMethod("POST");
    httpURLConnection_a.setUseCaches(false);
    httpURLConnection_a.setInstanceFollowRedirects(false);
    httpURLConnection_a.setDoOutput(true);

    String OUTPUT_DATA = "username=";
    OUTPUT_DATA += username;
    OUTPUT_DATA += "&password=";
    OUTPUT_DATA += password;
    OUTPUT_DATA += "&submit=";
    OUTPUT_DATA += "&lt=" + LOGIN_PARAM_lt;
    OUTPUT_DATA += "&execution=" + LOGIN_PARAM_execution;
    OUTPUT_DATA += "&_eventId=" + LOGIN_PARAM__eventId;
    OUTPUT_DATA += "&rmShown=" + LOGIN_PARAM_rmShown;

    httpURLConnection_a.setRequestProperty("Cookie",
            "route=" + ROUTE
                    + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; JSESSIONID="
                    + LOGIN_JSESSIONID + "; BIGipServeridsnew.xidian.edu.cn=" + BIGIP_SERVER_IDS_NEW + ";");

    httpURLConnection_a.connect();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection_a.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(OUTPUT_DATA);
    outputStreamWriter.flush();
    outputStreamWriter.close();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection_a.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("a");
    if (elements.size() == 0)
        return false;
    String SYS_LOCATION = elements.get(0).attr("href");

    URL sys_location = new URL(SYS_LOCATION);
    HttpURLConnection httpUrlConnection_b = (HttpURLConnection) sys_location.openConnection();
    httpUrlConnection_b.setInstanceFollowRedirects(false);
    httpUrlConnection_b.connect();
    List<String> cookies_to_set = httpUrlConnection_b.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(11, e.indexOf(";"));
    httpURLConnection_a.disconnect();
    httpUrlConnection_b.disconnect();
    return checkIsLogin(username);
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public Map<String, List<String>> getHeaders(String url) throws IOException {

    logger.log(Level.INFO, "Getting HEAD from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.setDoInput(true);// w w w .j  av  a  2  s  .co m
    connection.setRequestMethod("HEAD");
    connection.connect();

    // Get the headers
    return disconnectAndReturn(connection, connection.getHeaderFields());
}

From source file:org.callimachusproject.test.WebResource.java

private WebResource findLink(String rel, boolean rev, String... types)
        throws IOException, MalformedURLException, ProtocolException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("OPTIONS");
    Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode());
    for (Map.Entry<String, List<String>> e : con.getHeaderFields().entrySet()) {
        if (!"Link".equalsIgnoreCase(e.getKey()))
            continue;
        for (String header : e.getValue()) {
            Assert.assertNotNull(header);
            Matcher m = LINK.matcher(header);
            while (m.find()) {
                if (rev && !header.contains("rev="))
                    continue;
                String href = m.group(1);
                String a = m.group(2);
                String r = m.group(3) != null ? m.group(3) : m.group(4);
                String t = m.group(5) != null ? m.group(5) : m.group(6);
                if (a != null && !TermFactoryImpl.newInstance(uri).resolve(a).equals(uri))
                    continue;
                if (!rel.equals(r))
                    continue;
                if (types.length == 0 || t == null)
                    return ref(href);
                for (String type : types) {
                    for (String t1 : t.split("\\s+")) {
                        if (t1.length() > 0 && t1.startsWith(type)) {
                            return ref(href);
                        }/*from   ww  w.  j av a2 s. c  o  m*/
                    }
                }
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<").append(uri).append("?").append(rel);
    sb.append(">");
    if (rev) {
        sb.append("; rev=\"");
    } else {
        sb.append("; rel=\"");
    }
    sb.append(rel).append("\"; type=\"");
    for (String type : types) {
        sb.append(type).append(' ');
    }
    sb.setLength(sb.length() - 1);
    sb.append("\"");
    Assert.assertEquals(sb.toString(), con.getHeaderField("Link"));
    return null;
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

private void testDelete(int statusCode) throws Exception {
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpUrlConnectionProvider providerProvider = new HttpUrlConnectionProvider(connection);
    final String id = "1";

    when(connection.getResponseCode()).thenReturn(statusCode);
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA));
    when(connection.getErrorStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA));
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", providerProvider);

    HeaderAndBody result = provider.delete(id);

    assertArrayEquals(EMPTY_DATA, result.getBody());
    assertEquals("DELETE", connection.getRequestMethod());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertEquals(id, providerProvider.id);
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static <R> R fetchWithFollowRedirects(final Method method, final URL url,
        final HttpStreamHandler<R> streamHandler, final int redirectCount)
        throws IOException, URISyntaxException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {//from w w w  .  j ava 2 s .  co  m
        connection.setRequestMethod(method.toString());
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS));
        connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS));
        connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser.
        //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong.
        connection.connect();

        InputStream is = null;
        try {
            final int responseCode = connection.getResponseCode();

            // For some reason some devices do not follow redirects. :(
            if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers.  Its HTTP spec.
                if (redirectCount >= MAX_REDIRECTS)
                    throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS);
                final String locationHeader = connection.getHeaderField("Location");
                if (locationHeader == null)
                    throw new HttpResponseException(responseCode,
                            "Location header missing.  Headers present: " + connection.getHeaderFields() + ".");
                connection.disconnect();

                final URL locationUrl;
                if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) {
                    locationUrl = new URL(locationHeader);
                } else {
                    locationUrl = url.toURI().resolve(locationHeader).toURL();
                }
                return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1);
            }

            if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers.  Its HTTP spec.
                throw new NotOkResponseException(responseCode, connection, url);
            }

            is = connection.getInputStream();
            final int contentLength = connection.getContentLength();
            if (contentLength < 1)
                LOG.w("Content-Length=%s for %s.", contentLength, url);
            return streamHandler.handleStream(connection, is, contentLength);
        } finally {
            IoHelper.closeQuietly(is);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

@Test
public void testPost() throws Exception {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(RESPONSE_DATA.length);
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", new HttpUrlConnectionProvider(connection));

    doReturn(HttpStatus.SC_OK).when(connection).getResponseCode();
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(RESPONSE_DATA));
    when(connection.getOutputStream()).thenReturn(outputStream);
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HeaderAndBody result = provider.post(REQUEST_DATA);
    assertEquals("POST", connection.getRequestMethod());
    assertArrayEquals(RESPONSE_DATA, result.getBody());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertArrayEquals(RESPONSE_DATA, outputStream.toByteArray());

}