Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:test.ShopThreadSrc.java

private HttpURLConnection getHttpGetConn(String url) throws Exception {
    HttpURLConnection conn;
    // Acts like a browser
    URL obj = new URL(url);
    conn = (HttpURLConnection) obj.openConnection();
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }//from   w  ww  .  jav  a  2 s.  c  o  m
    conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Host", "consignment.5173.com");
    conn.setRequestProperty("Referer", url);
    System.out.println(conn.getRequestProperties());
    return conn;
}

From source file:org.seagatesoft.sde.tagtreebuilder.DOMParserTagTreeBuilder.java

public TagTree buildTagTree(String htmlDocument, boolean ignoreFormattingTags)
        throws IOException, SAXException {
    URL url = new URL(htmlDocument);
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
    BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));
    baseURI = url.getProtocol() + "://" + url.getHost();
    return buildTagTree(new InputSource(in), ignoreFormattingTags, htmlDocument);
}

From source file:io.divolte.server.DslRecordMapperTest.java

private EventPayload request(String location, String referer) throws IOException, InterruptedException {
    final URL url = referer == null
            ? new URL(String.format(DIVOLTE_URL_STRING, server.port) + DIVOLTE_URL_QUERY_STRING + "&l="
                    + URLEncoder.encode(location, StandardCharsets.UTF_8.name()))
            : new URL(String.format(DIVOLTE_URL_STRING, server.port) + DIVOLTE_URL_QUERY_STRING + "&l="
                    + URLEncoder.encode(location, StandardCharsets.UTF_8.name()) + "&r="
                    + URLEncoder.encode(referer, StandardCharsets.UTF_8.name()));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("User-Agent", USER_AGENT);
    conn.addRequestProperty("Cookie", "custom_cookie=custom_cookie_value;");
    conn.addRequestProperty("X-Divolte-Test", "first");
    conn.addRequestProperty("X-Divolte-Test", "second");
    conn.addRequestProperty("X-Divolte-Test", "last");
    conn.setRequestMethod("GET");

    assertEquals(200, conn.getResponseCode());

    return server.waitForEvent();
}

From source file:net.andylizi.colormotd.Updater.java

private boolean checkUpdate() {
    if (file != null && file.exists()) {
        cancel();// w w  w  .ja  v  a 2 s.c o  m
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", userAgent);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= ColorMOTD.buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

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

public void testCookie() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-SetCookie", "four=2*2");
    conn.connect();/*from w  ww . java  2 s .co m*/
    assertEquals("four=2*2", conn.getHeaderField("Set-Cookie"));
}

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

public void testStatus() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-ResponseStatus", "302 Temporary Redirect");
    conn.connect();/* w  w w  .j  av a  2s . c  o  m*/
    assertEquals(302, conn.getResponseCode());
    assertEquals("Temporary Redirect", conn.getResponseMessage());
}

From source file:com.juick.android.Utils.java

public static RESTResponse postJSON(final Context context, final String url, final String data,
        final String contentType) {
    final URLAuth authorizer = getAuthorizer(url);
    final RESTResponse[] ret = new RESTResponse[] { null };
    final boolean[] cookieCleared = new boolean[] { false };
    authorizer.authorize(context, false, false, url, new Function<Void, String>() {
        @Override/*  ww w  .j a  v  a  2 s  .c om*/
        public Void apply(String myCookie) {
            final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH);
            if (noAuthRequested)
                myCookie = null;
            HttpURLConnection conn = null;
            try {
                String nurl = authorizer.authorizeURL(url, myCookie);
                URL jsonURL = new URL(nurl);
                conn = (HttpURLConnection) jsonURL.openConnection();
                if (contentType != null) {
                    conn.addRequestProperty("Content-Type", contentType);
                }
                authorizer.authorizeRequest(context, conn, myCookie, nurl);

                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.close();

                URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false);
                try {
                    if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) {
                        ret[0] = new RESTResponse(NO_AUTH, false, null);
                    } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) {
                        cookieCleared[0] = true; // don't enter loop
                        final Function<Void, String> thiz = this;
                        authorizer.clearCookie(context, new Runnable() {
                            @Override
                            public void run() {
                                authorizer.authorize(context, true, false, url, thiz);
                            }
                        });
                    } else {
                        if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) {
                            InputStream inputStream = conn.getInputStream();
                            ret[0] = streamToString(inputStream, null);
                            inputStream.close();
                        } else {
                            ret[0] = new RESTResponse(
                                    "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false,
                                    null);
                        }
                    }
                } finally {
                    conn.disconnect();
                }
            } catch (Exception e) {
                Log.e("getJSON", e.toString());
                ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return null; //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    while (ret[0] == null) { // bad, but true
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return ret[0];
}

From source file:net.andylizi.colormotd.anim.updater.Updater.java

private boolean checkUpdate() {
    if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) {
        cancel();//w w w.  j av  a 2s  .  c om
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", USER_AGENT);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

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

public void testResponseLength() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-ResponseLength", "10");
    conn.connect();/*from   w w w .  ja v a2s .c  o  m*/
    final InputStream inputStream = conn.getInputStream();
    assertEquals(10, IOUtils.toByteArray(inputStream).length);
    inputStream.close();
}

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 w w w. j av a2s  .co m*/
    assertEquals(200, conn.getResponseCode());
    assertEquals("OK", conn.getResponseMessage());
    assertEquals("/abcd", conn.getHeaderField("Location"));
    assertEquals("none", conn.getHeaderField("X-Dummy"));
}