Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:ch.njol.skript.Updater.java

/**
 * @param sender Sender to receive messages
 * @param download Whether to directly download the newest version if one is found
 * @param isAutomatic/*w  ww  .ja  v a  2 s.  co  m*/
 */
static void check(final CommandSender sender, final boolean download, final boolean isAutomatic) {
    stateLock.writeLock().lock();
    try {
        if (state == UpdateState.CHECK_IN_PROGRESS || state == UpdateState.DOWNLOAD_IN_PROGRESS)
            return;
        state = UpdateState.CHECK_IN_PROGRESS;
    } finally {
        stateLock.writeLock().unlock();
    }
    if (!isAutomatic || Skript.logNormal())
        Skript.info(sender, "" + m_checking);
    Skript.newThread(new Runnable() {
        @Override
        public void run() {
            infos.clear();

            InputStream in = null;
            try {
                final URLConnection conn = new URL(filesURL).openConnection();
                conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)");
                in = conn.getInputStream();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(in,
                        conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()));
                try {
                    final String line = reader.readLine();
                    if (line != null) {
                        final JSONArray a = (JSONArray) JSONValue.parse(line);
                        for (final Object o : a) {
                            final Object name = ((JSONObject) o).get("name");
                            if (!(name instanceof String)
                                    || !((String) name).matches("\\d+\\.\\d+(\\.\\d+)?( \\(jar( only)?\\))?"))// not the default version pattern to not match beta/etc. versions
                                continue;
                            final Object url = ((JSONObject) o).get("downloadUrl");
                            if (!(url instanceof String))
                                continue;

                            final Version version = new Version(((String) name).contains(" ")
                                    ? "" + ((String) name).substring(0, ((String) name).indexOf(' '))
                                    : ((String) name));
                            if (version.compareTo(Skript.getVersion()) > 0) {
                                infos.add(new VersionInfo((String) name, version, (String) url));
                            }
                        }
                    }
                } finally {
                    reader.close();
                }

                if (!infos.isEmpty()) {
                    Collections.sort(infos);
                    latest.set(infos.get(0));
                } else {
                    latest.set(null);
                }

                getChangelogs(sender);

                final String message = infos.isEmpty()
                        ? (Skript.getVersion().isStable() ? "" + m_running_latest_version
                                : "" + m_running_latest_version_beta)
                        : "" + m_update_available;
                if (isAutomatic && !infos.isEmpty()) {
                    Skript.adminBroadcast(message);
                } else {
                    Skript.info(sender, message);
                }

                if (download && !infos.isEmpty()) {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.DOWNLOAD_IN_PROGRESS;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                    download_i(sender, isAutomatic);
                } else {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.CHECKED_FOR_UPDATE;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                }
            } catch (final IOException e) {
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(ExceptionUtils.toString(e));
                    if (sender != null)
                        Skript.error(sender, m_check_error.toString());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } catch (final Exception e) {
                if (sender != null)
                    Skript.error(sender, m_internal_error.toString());
                Skript.exception(e, "Unexpected error while checking for a new version of Skript");
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (final IOException e) {
                    }
                }
            }
        }
    }, "Skript update thread").start();
}

From source file:com.moviejukebox.tools.WebBrowser.java

/**
 * Check the URL to see if it's one of the special cases that needs to be worked around
 *
 * @param URL The URL to check/* w  ww.j  a  v a  2 s.co m*/
 * @param cnx The connection that has been opened
 */
private static void checkRequest(URLConnection checkCnx) {
    String checkUrl = checkCnx.getURL().getHost().toLowerCase();

    // TODO: Move these workarounds into a property file so they can be overridden at runtime
    // A workaround for the need to use a referrer for thetvdb.com
    if (checkUrl.contains("thetvdb")) {
        checkCnx.setRequestProperty("Referer", "http://forums.thetvdb.com/");
    }

    // A workaround for the kinopoisk.ru site
    if (checkUrl.contains("kinopoisk")) {
        checkCnx.setRequestProperty("Accept", "text/html, text/plain");
        checkCnx.setRequestProperty("Accept-Language", "ru");
        checkCnx.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    }
}

From source file:BihuHttpUtil.java

public static String doHttpPost(String xmlInfo, String URL) {
    System.out.println("??:" + xmlInfo);
    byte[] xmlData = xmlInfo.getBytes();
    InputStream instr = null;//from   ww w . j  a va 2s.c  o m
    java.io.ByteArrayOutputStream out = null;
    try {
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);
        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("Content-Type", "text/xml");
        urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
        System.out.println(String.valueOf(xmlData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(xmlData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            System.out.println("");
        }
        System.out.println("?:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        e.printStackTrace();
        return "0";
    } finally {
        try {
            out.close();
            instr.close();
        } catch (Exception ex) {
            return "0";
        }
    }
}

From source file:com.omertron.thetvdbapi.tools.WebBrowser.java

/**
 * Set the header information for the connection
 *
 * @param cnx//  w  w  w  .  ja v  a  2 s  . c om
 */
private static void sendHeader(URLConnection cnx) {
    if (BROWSER_PROPERTIES.isEmpty()) {
        BROWSER_PROPERTIES.put("User-Agent", "Mozilla/5.25 Netscape/5.0 (Windows; I; Win95)");
    }

    // send browser properties
    for (Map.Entry<String, String> browserProperty : BROWSER_PROPERTIES.entrySet()) {
        cnx.setRequestProperty(browserProperty.getKey(), browserProperty.getValue());
    }
    // send cookies
    String cookieHeader = createCookieHeader(cnx);
    if (!cookieHeader.isEmpty()) {
        cnx.setRequestProperty("Cookie", cookieHeader);
    }
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

public static void addCommonHeaders(URLConnection connection) {
    HashMap<String, String> commonHeaders = getCommonHeaders();
    Set<String> keys = commonHeaders.keySet();
    for (String key : keys) {
        connection.setRequestProperty(key, commonHeaders.get(key));
    }/*w w w.j a va2  s  .  c o  m*/
}

From source file:org.deegree.commons.proxy.ProxySettings.java

/**
 * This method should be used everywhere instead of <code>URL.openConnection()</code>, as it copes with proxies that
 * require user authentication./*  w  ww.  j  ava2 s  .  com*/
 * 
 * @param url
 * @param user
 * @param pass
 * @return connection
 * @throws IOException
 */
public static URLConnection openURLConnection(URL url, String user, String pass) throws IOException {
    URLConnection conn = url.openConnection();
    if (user != null) {
        // TODO evaluate java.net.Authenticator
        String userAndPass = Base64.encodeBase64String((user + ":" + pass).getBytes());
        conn.setRequestProperty("Proxy-Authorization", "Basic " + userAndPass);
    }
    // TODO should this be a method parameter?
    conn.setConnectTimeout(5000);
    return conn;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

/**
 * Iterates the policies defined in the props object to ensure they are loaded locally. Policies are
 * searched for in the following order: - see if the current properties has a "&lt;PolicyID&gt;.file"
 * entry and that file exists in the local directory - if not, see if the file exists in the local
 * directory; if so create a ".file" property for it. - if not, get the "&lt;PolicyID&gt;.url" property
 * and try to GET the policy from that location (and set the ".file" property) If the ".file" property is
 * created, then true is returned to tell the caller that the props object changed.
 *
 * @param props/*from  w  ww  .j a  va  2s  . c o m*/
 * @return true/false if anything was changed in the props object
 * @throws PAPException
 */
public static synchronized boolean cachePolicies(Properties props) throws PAPException {
    boolean changed = false;
    String[] lists = new String[2];
    lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
    lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
    for (String list : lists) {
        //
        // Check for a null or empty parameter
        //
        if (list == null || list.length() == 0) {
            continue;
        }
        Iterable<String> policies = Splitter.on(',').trimResults().omitEmptyStrings().split(list);
        for (String policy : policies) {
            boolean policyExists = false;

            // First look for ".file" property and verify the file exists
            String propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_FILE);
            if (propLocation != null) {
                //
                // Does it exist?
                //
                policyExists = Files.exists(Paths.get(propLocation));
                if (!policyExists) {
                    logger.warn("Policy file " + policy + " expected at " + propLocation + " does NOT exist.");
                }
            }

            // If ".file" property does not exist, try looking for the local file anyway
            // (it might exist without having a ".file" property set for it)
            if (!policyExists) {
                //
                // Now construct the output file name
                //
                Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), policy);
                //
                // Double check to see if we pulled it at some point
                //
                policyExists = Files.exists(outFile);
                if (policyExists) {
                    //
                    // Set the property so the PDP engine doesn't have
                    // to pull it from the URL but rather the FILE.
                    //
                    logger.info("Policy does exist: " + outFile.toAbsolutePath().toString());
                    props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
                            outFile.toAbsolutePath().toString());
                    //
                    // Indicate that there were changes made to the properties
                    //
                    changed = true;
                } else {

                    // File does not exist locally, so we need to get it from the location given in the
                    // ".url" property (which MUST exist)

                    //
                    // There better be a URL to retrieve it
                    //
                    propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_URL);
                    if (propLocation != null) {
                        //
                        // Get it
                        //
                        URL url = null;
                        try {
                            //
                            // Create the URL
                            //
                            url = new URL(propLocation);
                            logger.info("Pulling " + url.toString());
                            //
                            // Open the connection
                            //
                            URLConnection urlConnection = url.openConnection();
                            urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
                                    XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
                            //
                            // Copy it to disk
                            //
                            try (InputStream is = urlConnection.getInputStream();
                                    OutputStream os = new FileOutputStream(outFile.toFile())) {
                                IOUtils.copy(is, os);
                            }
                            //
                            // Now save it in the properties as a .file
                            //
                            logger.info("Pulled policy: " + outFile.toAbsolutePath().toString());
                            props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
                                    outFile.toAbsolutePath().toString());
                            //
                            // Indicate that there were changes made to the properties
                            //
                            changed = true;
                        } catch (Exception e) {
                            if (e instanceof MalformedURLException) {
                                logger.error("Policy '" + policy + "' had bad URL in new configuration, URL='"
                                        + propLocation + "'");
                            } else {
                                logger.error("Error while retrieving policy " + policy + " from URL "
                                        + url.toString() + ", e=" + e);
                            }
                        }
                    } else {
                        logger.error("Policy " + policy + " does NOT exist and does NOT have a URL");
                    }
                }
            }
        }
    }
    return changed;
}

From source file:BihuHttpUtil.java

/**
 * ? URL ??POST//  ww  w  .j av a  2 s. c  o  m
 *
 * @param url
 *               ?? URL
 * @param param
 *               ?? name1=value1&name2=value2 ?
 * @param sessionId
 *             ???
 * @return ??
 */
public static Map<String, String> sendPost(String url, String param, String sessionId) {
    Map<String, String> resultMap = new HashMap<String, String>();
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        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");
        if (StringUtils.isNotBlank(sessionId)) {
            conn.setRequestProperty("Cookie", sessionId);
        }
        // ??POST
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // ?URLConnection?
        out = new PrintWriter(conn.getOutputStream());
        // ???
        out.print(param);
        // flush?
        out.flush();
        // BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String cookieValue = conn.getHeaderField("Set-Cookie");
        resultMap.put("cookieValue", cookieValue);
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("?? POST ?" + e);
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    resultMap.put("result", result);
    return resultMap;
}

From source file:org.y20k.transistor.helpers.MetadataHelper.java

public static void prepareMetadata(final String mStreamUri, final Station mStation, final Context mContext)
        throws IOException {
    metaDataThread = new Thread(new Runnable() {

        @Override//w ww  .j a  v  a  2s. c o m
        public void run() {
            try {
                URLConnection connection = new URL(mStreamUri).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestProperty("Icy-MetaData", "1");
                connection.connect();

                InputStream in = connection.getInputStream();

                byte buf[] = new byte[16384]; // one second of 128kbit stream
                int count = 0;
                int total = 0;
                int metadataSize = 0;
                final int metadataOffset = connection.getHeaderFieldInt("icy-metaint", 0);
                int bitRate = Math.max(connection.getHeaderFieldInt("icy-br", 128), 32);
                LogHelper.v(LOG_TAG, "createProxyConnection: connected, icy-metaint " + metadataOffset
                        + " icy-br " + bitRate);
                Thread thisThread = Thread.currentThread();
                int thisThreadCounter = 0;
                while (true && metaDataThread == thisThread) {
                    if (thisThreadCounter > 20) { //only try 20 times and terminate thread to be sure getting metadata
                        LogHelper.v(LOG_TAG,
                                "thisThreadCounter: Upper Break at thisThreadCounter=" + thisThreadCounter);
                        break;
                    }
                    thisThreadCounter++;
                    count = Math.min(in.available(), buf.length);
                    if (count <= 0) {
                        count = Math.min(bitRate * 64, buf.length); // buffer half-second of stream data
                    }
                    if (metadataOffset > 0) {
                        count = Math.min(count, metadataOffset - total);
                    }

                    count = in.read(buf, 0, count);
                    if (count == 0) {
                        continue;
                    }
                    if (count < 0) {
                        LogHelper.v(LOG_TAG, "thisThreadCounter: Break at -count < 0- thisThreadCounter="
                                + thisThreadCounter);
                        break;
                    }
                    total += count;
                    if (metadataOffset > 0 && total >= metadataOffset) {
                        // read metadata
                        total = 0;
                        count = in.read();
                        if (count < 0) {
                            LogHelper.v(LOG_TAG, "thisThreadCounter: Break2 at -count < 0- thisThreadCounter="
                                    + thisThreadCounter);
                            break;
                        }
                        count *= 16;
                        metadataSize = count;
                        if (metadataSize == 0) {
                            continue;
                        }
                        // maximum metadata length is 4080 bytes
                        total = 0;
                        while (total < metadataSize) {
                            count = in.read(buf, total, count);
                            if (count < 0) {
                                LogHelper.v(LOG_TAG,
                                        "thisThreadCounter: Break3 at -count < 0- thisThreadCounter="
                                                + thisThreadCounter);
                                break;
                            }
                            if (count == 0) {
                                continue;
                            }
                            total += count;
                            count = metadataSize - total;
                        }
                        total = 0;
                        String[] metadata = new String(buf, 0, metadataSize, StandardCharsets.UTF_8).split(";");
                        for (String s : metadata) {
                            if (s.indexOf(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER) == 0 && s
                                    .length() >= TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length() + 1) {
                                //handleMetadataString(s.substring(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1));
                                String metadata2 = s.substring(
                                        TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1);
                                if (metadata2 != null && metadata2.length() > 0) {
                                    // send local broadcast
                                    Intent i = new Intent();
                                    i.setAction(TransistorKeys.ACTION_METADATA_CHANGED);
                                    i.putExtra(TransistorKeys.EXTRA_METADATA, metadata2);
                                    i.putExtra(TransistorKeys.EXTRA_STATION, mStation);
                                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(i);

                                    // save metadata to shared preferences
                                    SharedPreferences settings = PreferenceManager
                                            .getDefaultSharedPreferences(mContext);
                                    SharedPreferences.Editor editor = settings.edit();
                                    editor.putString(TransistorKeys.PREF_STATION_METADATA, metadata2);
                                    editor.apply();

                                    //done getting the metadata
                                    LogHelper.v(LOG_TAG, "thisThreadCounter: Lower Break at thisThreadCounter="
                                            + thisThreadCounter);
                                    break;
                                }
                                // break;
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                LogHelper.e(LOG_TAG, e.getMessage());
            }
        }

    });
    metaDataThread.start();
}

From source file:org.deegree.commons.proxy.ProxySettings.java

/**
 * This method should be used everywhere instead of <code>URL.openConnection()</code>, as it copes with proxies that
 * require user authentication and http basic authentication.
 * // w w w.ja  v  a2s. co m
 * @param url
 * @return connection
 * @throws IOException
 */
public static URLConnection openURLConnection(URL url, String proxyUser, String proxyPass, String httpUser,
        String httpPass) throws IOException {
    URLConnection conn = url.openConnection();
    if (proxyUser != null) {
        // TODO evaluate java.net.Authenticator
        String userAndPass = Base64.encodeBase64String((proxyUser + ":" + proxyPass).getBytes());
        conn.setRequestProperty("Proxy-Authorization", "Basic " + userAndPass);
    }
    if (httpUser != null) {
        // TODO evaluate java.net.Authenticator
        String userAndPass = Base64.encodeBase64String((httpUser + ":" + httpPass).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + userAndPass);
    }
    // TODO should this be a method parameter?
    conn.setConnectTimeout(5000);
    return conn;
}