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.adguard.commons.web.UrlUtils.java

/**
 * Downloads content from the specified url using specified proxy (or do not using it) and timeouts.
 * Returns null if there's an error.// www . ja  va  2  s.  c  o  m
 *
 * @param url           url
 * @param proxy         proxy to use
 * @param readTimeout   read timeout
 * @param socketTimeout connection timeout
 * @return Downloaded string
 */
public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {
        connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy));
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
        connection.setReadTimeout(readTimeout);
        connection.setConnectTimeout(socketTimeout);
        connection.connect();
        if (connection.getResponseCode() >= 400) {
            throw new IOException("Response status is " + connection.getResponseCode());
        }

        if (connection.getResponseCode() >= 301) {
            String location = connection.getHeaderField("Location");
            // HttpURLConnection does not follow redirects from HTTP to HTTPS
            // So we handle it manually
            return downloadString(new URL(location), proxy, readTimeout, socketTimeout, encoding);
        }

        if (connection.getResponseCode() == 204) {
            return StringUtils.EMPTY;
        }

        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream, encoding);
    } catch (IOException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Error downloading string from {}:\r\n", url, ex);
        } else {
            LOG.warn("Cannot download string from {}: {}", url, ex.getMessage());
        }
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.melniqw.instagramsdk.Network.java

private static String sendDummyRequest(String url, String body, Request request) throws IOException {
    HttpURLConnection connection = null;
    try {/*from  ww  w  .  ja v a  2  s .co  m*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        //            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        if (request == Request.GET) {
            connection.setDoOutput(false);
            connection.setRequestMethod("GET");
        } else if (request == Request.POST) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        }
        if (REQUEST_ENABLE_COMPRESSION)
            connection.setRequestProperty("Accept-Encoding", "gzip");
        if (request == Request.POST)
            connection.getOutputStream().write(body.getBytes("utf-8"));
        int code = connection.getResponseCode();
        System.out.println(TAG + " responseCode = " + code);
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1)
            throw new WrongResponseCodeException("Network error");
        // ?    200
        //on error can also read error stream from connection.
        InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
        String encoding = connection.getHeaderField("Content-Encoding");
        if (encoding != null && encoding.equalsIgnoreCase("gzip"))
            inputStream = new GZIPInputStream(inputStream);
        String response = Utils.convertStreamToString(inputStream);
        System.out.println(TAG + " response = " + response);
        return response;
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java

public void testQueryRedirect() throws Exception {
    URL url = new URI("http", null, "localhost", HTTP_SERVER_PORT, "/path", "redirect=/a/b/c/d?q", null)
            .toURL();//  w  w w  .j  av  a 2 s . c  o  m
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    assertEquals(302, conn.getResponseCode());
    assertEquals("Temporary Redirect", conn.getResponseMessage());
    assertEquals("/a/b/c/d?q", conn.getHeaderField("Location"));
}

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

@Test
public void queryESAllPrimWithEntityTypeCastInExpand() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim(0)?$expand=NavPropertyETTwoPrimOne/olingo.odata.test1.ETBase");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
    connection.connect();/*from www.j  av  a2s  .c  o  m*/

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

    final String content = IOUtils.toString(connection.getInputStream());
    assertTrue(content.contains("\"PropertyInt16\":0," + "\"PropertyString\":\"\","
            + "\"PropertyBoolean\":false," + "\"PropertyByte\":0," + "\"PropertySByte\":0,"
            + "\"PropertyInt32\":0," + "\"PropertyInt64\":0," + "\"PropertySingle\":0.0,"
            + "\"PropertyDouble\":0.0," + "\"PropertyDecimal\":0," + "\"PropertyBinary\":\"\","
            + "\"PropertyDate\":\"1970-01-01\"," + "\"PropertyDateTimeOffset\":\"2005-12-03T00:00:00Z\","
            + "\"PropertyDuration\":\"PT0S\"," + "\"PropertyGuid\":\"76543201-23ab-cdef-0123-456789cccddd\","
            + "\"PropertyTimeOfDay\":\"00:01:01\",\"NavPropertyETTwoPrimOne\":{"
            + "\"@odata.type\":\"#olingo.odata.test1.ETBase\","
            + "\"PropertyInt16\":111,\"PropertyString\":\"TEST A\","
            + "\"AdditionalPropertyString_5\":\"TEST A 0815\"}"));
}

From source file:org.apache.hadoop.hbase.http.TestHttpServer.java

@Test
public void testNoCacheHeader() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    assertEquals("no-cache", conn.getHeaderField("Cache-Control"));
    assertEquals("no-cache", conn.getHeaderField("Pragma"));
    assertNotNull(conn.getHeaderField("Expires"));
    assertNotNull(conn.getHeaderField("Date"));
    assertEquals(conn.getHeaderField("Expires"), conn.getHeaderField("Date"));
    assertEquals("DENY", conn.getHeaderField("X-Frame-Options"));
}

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

public String getRedirectLocation() throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("HEAD");
    int code = con.getResponseCode();
    if (!(code == 301 || code == 303 || code == 302 || code == 307 || code == 308))
        Assert.assertEquals(con.getResponseMessage(), 302, code);
    return con.getHeaderField("Location");
}

From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java

public void testHeaders() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-SetHeaders", "Location: /abcd|X-Dummy: none");
    conn.connect();//from ww w .  ja v  a2  s .c  o  m
    assertEquals(200, conn.getResponseCode());
    assertEquals("OK", conn.getResponseMessage());
    assertEquals("/abcd", conn.getHeaderField("Location"));
    assertEquals("none", conn.getHeaderField("X-Dummy"));
}

From source file:org.apache.hadoop.hbase.http.TestHttpServer.java

@Test
public void testXFrameHeaderSameOrigin() throws Exception {
    Configuration conf = new Configuration();
    conf.set("hbase.http.filter.xframeoptions.mode", "SAMEORIGIN");

    HttpServer myServer = new HttpServer.Builder().setName("test").addEndpoint(new URI("http://localhost:0"))
            .setFindPort(true).setConf(conf).build();
    myServer.setAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE, conf);
    myServer.addServlet("echo", "/echo", EchoServlet.class);
    myServer.start();/*from   ww  w.j a va2s  .  c  o m*/

    String serverURL = "http://" + NetUtils.getHostPortString(myServer.getConnectorAddress(0));
    URL url = new URL(new URL(serverURL), "/echo?a=b&c=d");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    assertEquals("SAMEORIGIN", conn.getHeaderField("X-Frame-Options"));
    myServer.stop();
}

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

@Test
public void queryESMixPrimWithLambdaDerived_JsonMinimal_Olingo1122() throws Exception {
    URL url = new URL(SERVICE_URI + "ESMixPrimCollComp?$filter=CollPropertyComp/any"
            + "(f:f/olingo.odata.test1.CTBase/AdditionalPropString%20eq%20%27ADD%20TEST%27)");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
    connection.connect();/*  ww w. j  av  a2s . co  m*/

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

    final String content = IOUtils.toString(connection.getInputStream());
    assertTrue(content.contains(
            "\"value\":[{\"PropertyInt16\":32767," + "\"CollPropertyString\":[\"Employee1@company.example\","
                    + "\"Employee2@company.example\"," + "\"Employee3@company.example\"],"
                    + "\"PropertyComp\":{\"PropertyInt16\":111,\"PropertyString\":\"TEST A\"},"
                    + "\"CollPropertyComp\":[" + "{\"PropertyInt16\":123,\"PropertyString\":\"TEST 1\"},"
                    + "{\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
                    + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\","
                    + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\","
                    + "\"AdditionalPropString\":\"ADD TEST\"}]},"
                    + "{\"PropertyInt16\":7,\"CollPropertyString\":" + "[\"Employee1@company.example\","
                    + "\"Employee2@company.example\"," + "\"Employee3@company.example\"],"
                    + "\"PropertyComp\":{\"PropertyInt16\":222,\"PropertyString\":\"TEST B\"},"
                    + "\"CollPropertyComp\":[{\"PropertyInt16\":123,\"PropertyString\":\"TEST 1\"},"
                    + "{\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
                    + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\","
                    + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\","
                    + "\"AdditionalPropString\":\"ADD TEST\"}]},"
                    + "{\"PropertyInt16\":0,\"CollPropertyString\":[" + "\"Employee1@company.example\","
                    + "\"Employee2@company.example\"," + "\"Employee3@company.example\"],"
                    + "\"PropertyComp\":{\"PropertyInt16\":333,\"PropertyString\":\"TEST C\"},"
                    + "\"CollPropertyComp\":[" + "{\"PropertyInt16\":123,\"PropertyString\":\"TEST 1\"},"
                    + "{\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
                    + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\","
                    + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\","
                    + "\"AdditionalPropString\":\"ADD TEST\"}]}]"));
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * // www  .  j a  va2 s .c o m
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}