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.baidu.jprotobuf.rpc.client.SimpleHttpRequestExecutor.java

/**
 * Determine whether the given response is a GZIP response.
 * <p>Default implementation checks whether the HTTP "Content-Encoding"
 * header contains "gzip" (in any casing).
 * @param con the HttpURLConnection to check
 *//*  w  w  w .j  a v a2  s.  c  o  m*/
protected boolean isGzipResponse(HttpURLConnection con) {
    String encodingHeader = con.getHeaderField(HTTP_HEADER_CONTENT_ENCODING);
    return (encodingHeader != null && encodingHeader.toLowerCase().indexOf(ENCODING_GZIP) != -1);
}

From source file:mdretrieval.FileFetcher.java

public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException {
    String[] ret = new String[2];

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    String dest = destinationURL;
    URL url = new URL(dest);
    Proxy proxy = null;/* ww  w.  j  av  a2  s. c o  m*/

    if (ServerConstants.isProxyEnabled) {
        proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(ServerConstants.hostname, ServerConstants.port));
        urlConnection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        urlConnection = (HttpURLConnection) url.openConnection();
    }

    boolean redirect = false;

    int status = urlConnection.getResponseCode();
    if (Master.DEBUG_LEVEL >= Master.LOW)
        System.out.println("RESPONSE-CODE--> " + status);
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {
        String newUrl = urlConnection.getHeaderField("Location");
        dest = newUrl;
        urlConnection.disconnect();
        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println("REDIRECT--> " + newUrl);
        urlConnection = openMaybeProxyConnection(proxy, newUrl);
    }

    try {
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        urlConnection.setDoInput(true);
        //urlConnection.setDoOutput(true);            
        inputStream = urlConnection.getInputStream();
        ret[1] = urlConnection.getHeaderField("Content-Type");
    } catch (IllegalStateException e) {
        if (Master.DEBUG_LEVEL >= Master.LOW)
            System.out.println(" DEBUG: IllegalStateException");
        urlConnection.disconnect();
        HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest);
        conn2.setRequestMethod("GET");
        conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        conn2.setDoInput(true);
        inputStream = conn2.getInputStream();
        ret[1] = conn2.getHeaderField("Content-Type");
    }

    try {
        ret[0] = IOUtils.toString(inputStream);

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type"));
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        urlConnection.disconnect();
    }

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Done reading " + destinationURL);
    return ret;

}

From source file:com.google.android.apps.santatracker.service.RemoteApiProcessor.java

/**
 * Returns true if this application can handle requests of this version,
 * false otherwise. The current API version can be retrieved through:
 * <code>curl -sI 'http://santa-api.appspot.com/info' | grep X-Santa</code>
 *//*from www .  ja  v a2  s.  c o  m*/
protected boolean isValidHeader(HttpURLConnection connection) {

    String version = connection.getHeaderField(API_VERSION_FIELD);
    // if the version matches supported version, returns true, false if no
    // header is set or it is not recognised.
    return version != null && SUPPORTED_SANTA_HEADER_API.contains(version);

}

From source file:net.sparkeh.magisterlib.MagisterLib.java

public static String getAuthCookie(String APIUrl, String username, String password) throws Exception {
    URL obj = new URL(APIUrl + "sessie");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Cookie", "SESSION_ID=349c6fcb-f49a-47c4-b129-09158986155b");
    JSONObject o = new JSONObject();
    o.put("GebruikersNaam", username);
    o.put("Wachtwoord", password);
    o.put("IngelogdBlijven", false);
    o.put("GebruikersnaamOnthouden", false);
    con.setDoOutput(true);/*from   w  w w  .ja  v  a  2s. c om*/
    con.getOutputStream().write(o.toJSONString().getBytes("UTF-8"));
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + obj.getPath());
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    if (con.getHeaderFields().containsKey("Set-Cookie")) {
        String c = con.getHeaderField("Set-Cookie").toString();
        if (c.contains(";")) {
            String[] s = c.split(";");
            for (String k : s) {
                if (k.contains("SESSION_ID") && k.contains("=")) {
                    return k.split("=")[1].trim();
                }
            }
        }
    }
    return null;
}

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

private String getCookie(URL url, HttpConnectionInterceptorContext context) {
    try {//from  www .  j  a  va2s. c o m
        URL sessionURL = new URL(
                String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort()));

        HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded");
        conn.setRequestBody(sessionRequestBody);

        //when we request the session we need all interceptors except this one

        conn.requestInterceptors.addAll(context.connection.requestInterceptors);
        conn.requestInterceptors.remove(this);
        conn.responseInterceptors.addAll(context.connection.responseInterceptors);
        conn.responseInterceptors.remove(this);

        HttpURLConnection connection = conn.execute().getConnection();
        String cookieHeader = connection.getHeaderField("Set-Cookie");
        int responseCode = connection.getResponseCode();

        if (responseCode / 100 == 2) {

            if (sessionHasStarted(connection.getInputStream())) {
                return cookieHeader.substring(0, cookieHeader.indexOf(";"));
            } else {
                return null;
            }

        } else if (responseCode == 401) {
            shouldAttemptCookieRequest = false;
            logger.severe("Credentials are incorrect, cookie authentication will not be"
                    + " attempted again by this interceptor object");
        } else if (responseCode / 100 == 5) {
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth",
                    responseCode);
        } else {
            // catch any other response code
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, "
                    + "cookie authentication will not be attempted again", responseCode);
            shouldAttemptCookieRequest = false;
        }

    } catch (MalformedURLException e) {
        logger.log(Level.SEVERE, "Failed to create URL for _session endpoint", e);
    } catch (UnsupportedEncodingException e) {
        logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read cookie response header", e);
    }
    return null;
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private String extractSession(HttpURLConnection conn) throws ExtractException {
    String s;//from   w  w  w .  java2  s .  c om
    logger.info("Extracting session token... ");
    String cookie = conn.getHeaderField("Set-Cookie");
    if (cookie == null || cookie.isEmpty()) {
        throw new ExtractException("Could not find session token. Please check user and password.");
    }
    Pattern pattern = Pattern.compile("Session=([a-z0-9]*);");
    Matcher matcher = pattern.matcher(cookie);
    if (matcher.find()) {
        s = matcher.group(1);
        logger.debug("Extract session token " + s);
    } else {
        throw new ExtractException("Could not find session token. Please check user and password.");
    }
    return s;
}

From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

@Test
public void testAddAccessControlAllowOriginHeader() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }//from   www. j a v a  2 s .  co  m

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addAfterResponse(new AddAccessControlAllowOriginHeaderAfterResponse());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2611/test";

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:org.cytoscape.app.internal.net.server.AddAllowOriginHeaderTest.java

@Test
public void testAddAccessControlAllowOriginHeader() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }/*from  www. j  ava2 s. c o  m*/

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addAfterResponse(new AddAllowOriginHeader());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2611/test";

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:org.cytoscape.app.internal.net.server.OriginOptionsBeforeResponseTest.java

@Test
public void testOptions() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2610));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }//from   ww w .j a v  a  2  s  . com

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addBeforeResponse(new OriginOptionsBeforeResponse());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2610/test";

    connection = connectToURL(url, "OPTIONS");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Methods"), "POST, PUT, GET, OPTIONS");
    assertEquals(connection.getHeaderField("Access-Control-Max-Age"), "1");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Headers"), "origin, accept");

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:com.ris.mobile.ecloud.util.AbFileUtil.java

/**
 * ???xx.??./*w  w w. j a v a 2s .c o  m*/
 * @param connection 
 * @return ??
 */
public static String getRealFileName(HttpURLConnection connection) {
    String name = null;
    try {
        if (connection == null) {
            return name;
        }
        if (connection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mime = connection.getHeaderField(i);
                if (mime == null) {
                    break;
                }
                // "Content-Disposition","attachment; filename=1.txt"
                // Content-Length
                if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                    if (m.find()) {
                        return m.group(1).replace("\"", "");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        //AbLogUtil.e(AbFileUtil.class, "???");
    }
    return name;
}