Example usage for java.net URLConnection addRequestProperty

List of usage examples for java.net URLConnection addRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection 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:org.apache.cayenne.rop.http.HttpROPConnector.java

protected void addAuthHeader(URLConnection connection) {
    String basicAuth = ROPUtil.getBasicAuth(username, password);

    if (basicAuth != null) {
        connection.addRequestProperty("Authorization", basicAuth);
    }/*from   w  ww . j a v  a2 s  .c om*/
}

From source file:com.md87.charliebravo.commands.DefineCommand.java

public void execute(final InputHandler handler, Response response, String line)
        throws MalformedURLException, IOException, JSONException {
    URL url = new URL("http://apps.md87.co.uk/services/wiktionary/?query="
            + URLEncoder.encode(line, Charset.defaultCharset().name()));
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer", "http://chris.smith.name/");

    String input;/*from w  w w . jav  a2 s.c  o  m*/
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while ((input = reader.readLine()) != null) {
        builder.append(input);
    }

    JSONObject json = new JSONObject(builder.toString());
    if (json.getInt("responseStatus") != 200) {
        throw new IOException(json.getString("responseDetails"));
    }

    if (json.getJSONArray("responseData").length() == 0) {
        response.sendMessage("There were no results for '" + line + "'", true);
    } else {
        final StringBuilder res = new StringBuilder();
        res.append("there ");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append("was 1 match");
        } else {
            res.append("were ");
            res.append(json.getJSONArray("responseData").length());
            res.append(" matches");
        }

        res.append(" for '");
        res.append(line);
        res.append("'");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append(". It is ");
        } else {
            res.append(". Result 1 is ");
        }

        final String name = json.getJSONArray("responseData").getJSONObject(0).getString("title");

        res.append('\'');
        res.append(name);
        res.append("', which has ");

        final int defs = json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions")
                .length();
        res.append(defs);

        res.append(" definition");

        if (defs != 1) {
            res.append("s, the first of which is");
        }

        res.append(": ");

        res.append(json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions").get(0));

        response.sendMessage(res.toString());
        response.addFollowup(new NextWordFollowup(json.getJSONArray("responseData"), 1));
        response.addFollowup(new NextDefinitionFollowup(
                json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions"), 1,
                new NextWordFollowup(json.getJSONArray("responseData"), 1)));
    }
}

From source file:org.callimachusproject.xml.InputSourceResolver.java

/**
 * returns null for 404 resources./*from   w w  w  . j  av  a 2s . co m*/
 */
private InputSource resolveURL(String systemId) throws IOException {
    URLConnection con = new URL(systemId).openConnection();
    con.addRequestProperty("Accept", getAcceptHeader());
    con.addRequestProperty("Accept-Encoding", "gzip");
    try {
        String base = con.getURL().toExternalForm();
        String type = con.getContentType();
        String encoding = con.getHeaderField("Content-Encoding");
        InputStream in = con.getInputStream();
        if (encoding != null && encoding.contains("gzip")) {
            in = new GZIPInputStream(in);
        }
        return create(type, in, base);
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        logger.warn("Could not resolve {}", systemId);
        throw e;
    }
}

From source file:org.nuxeo.ecm.platform.semanticentities.sources.DBpediaEntitySource.java

protected InputStream fetchSuggestions(String keywords, int maxSuggestions)
        throws UnsupportedEncodingException, MalformedURLException, IOException {
    String escapedKeywords = URLEncoder.encode(keywords, "UTF-8");
    String query = String.format(SUGGESTION_URL_PATTERN, escapedKeywords, maxSuggestions);
    log.debug(query);/*from   w  w  w.j a va 2 s. c om*/

    URL url = new URL(query);
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Accept", "application/xml");
    return connection.getInputStream();
}

From source file:com.servoy.extension.MarketPlaceExtensionProvider.java

private URLConnection ws_getConnection(String action, String acceptContentType, String extensionId,
        String version) throws Exception {
    String unescapedURL = MARKETPLACE_WS + action + "/" + extensionId //$NON-NLS-1$
            + (version != null ? "/" + version : "")/* + "?nodebug=true" */; //$NON-NLS-1$ //$NON-NLS-2$
    URL mpURL = new URI(null, null, unescapedURL, null).toURL(); // the URI should escape it correctly
    URLConnection urlConnection = mpURL.openConnection();

    urlConnection.addRequestProperty("accept", acceptContentType); //$NON-NLS-1$
    urlConnection.setConnectTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down
    urlConnection.setReadTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down or server doesn't want to respond

    return urlConnection;
}

From source file:org.apache.cayenne.rop.http.HttpROPConnector.java

protected void addSessionCookie(URLConnection connection) {
    RemoteSession session = clientConnection.getSession();
    if (session != null && session.getSessionId() != null) {
        connection.addRequestProperty("Cookie", SESSION_COOKIE_NAME + "=" + session.getSessionId());
    }/*from   ww w . j a  va  2 s.  c  o  m*/
}

From source file:net.hockeyapp.android.tasks.CheckUpdateTask.java

protected URLConnection createConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("User-Agent", "HockeySDK/Android");
    // connection bug workaround for SDK<=2.x
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
        connection.setRequestProperty("connection", "close");
    }//from  ww w .j ava 2s .  com
    return connection;
}

From source file:com.teozcommunity.teozfrank.duelme.util.UpdateChecker.java

/**
 * Query the API to find the latest approved file's details.
 *//* w  w  w.j a  v a 2  s .  c  o m*/
public void query() {
    URL url = null;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        // There was an error creating the URL

        e.printStackTrace();
        return;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            String versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            String versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            String versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            versionName = versionName.replaceAll("[a-zA-Z]", "");
            versionName = versionName.replaceAll(" ", "");

            String pluginVersion = plugin.getDescription().getVersion();

            pluginVersion = pluginVersion.replaceAll("Alpha", "");
            pluginVersion = pluginVersion.replaceAll("Beta", "");
            pluginVersion = pluginVersion.replaceAll("Release", "");
            pluginVersion = pluginVersion.replaceAll(" ", "");

            if (!versionName.equals(pluginVersion)) {
                this.updateAvailable = true;
                SendConsoleMessage.info("There is a new update available!");
                SendConsoleMessage.info("download it on bukkit dev " + ChatColor.YELLOW
                        + "http://dev.bukkit.org/bukkit-plugins/duelme/");
            } else {
                this.updateAvailable = false;
                SendConsoleMessage.info("plugin is up to date!");
            }

        } else {
            System.out.println("There are no files for this project");
        }
    } catch (IOException e) {
        // There was an error reading the query
        SendConsoleMessage.severe("There was an error checking for updates!");
        return;
    }
}

From source file:com.mstiles92.plugins.stileslib.updates.UpdateChecker.java

/**
 * The task to be run by the Bukkit scheduler that finds the latest published version on BukkitDev.
 *//*from  w ww .  j  ava  2s .  c  o  m*/
@Override
public void run() {
    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectIds=" + curseProjectId);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);
        connection.addRequestProperty("User-Agent", plugin.getName() + " (by mstiles92)");
        InputStream stream = connection.getInputStream();
        JSONParser parser = new JSONParser();
        Object o = parser.parse(new InputStreamReader(stream));
        stream.close();

        JSONArray array = (JSONArray) o;
        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            latestVersion = (String) latest.get("name");
            latestVersion = latestVersion.substring(1, latestVersion.length());
            updateAvailable = isNewerVersion(latestVersion);

            if (updateAvailable) {
                plugin.getLogger().info("Update available! New version: " + latestVersion);
                plugin.getLogger()
                        .info("More information available at http://dev.bukkit.org/bukkit-plugins/" + slug);
            }
        }
    } catch (IOException | ParseException | ClassCastException e) {
        plugin.getLogger()
                .info("Unable to check for updates. Will try again later. Error message: " + e.getMessage());
    }
}

From source file:ome.system.UpgradeCheck.java

/**
 * If the {@link #url} has been set to null or the empty string, then no
 * upgrade check will be performed (silently). If however the string is an
 * invalid URL, a warning will be printed.
 * /*w w w .  java  2  s.  c om*/
 * This method should <em>never</em> throw an exception.
 */
public void run() {

    // If null or empty, the upgrade check is disabled.
    if (url == null || url.length() == 0) {
        return; // EARLY EXIT!
    }

    StringBuilder query = new StringBuilder();
    try {
        query.append(url);
        query.append("?version=");
        query.append(URLEncoder.encode(version, "UTF-8"));
        query.append(";os.name=");
        query.append(URLEncoder.encode(System.getProperty("os.name"), "UTF-8"));
        query.append(";os.arch=");
        query.append(URLEncoder.encode(System.getProperty("os.arch"), "UTF-8"));
        query.append(";os.version=");
        query.append(URLEncoder.encode(System.getProperty("os.version"), "UTF-8"));
        query.append(";java.runtime.version=");
        query.append(URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8"));
        query.append(";java.vm.vendor=");
        query.append(URLEncoder.encode(System.getProperty("java.vm.vendor"), "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        // Internal issue
        set(null, uee);
        return;
    }

    URL _url;
    try {
        _url = new URL(query.toString());
    } catch (Exception e) {
        set(null, e);
        log.error("Invalid URL: " + query.toString());
        return;
    }

    BufferedInputStream bufIn = null;
    try {
        URLConnection conn = _url.openConnection();
        conn.setUseCaches(false);
        conn.addRequestProperty("User-Agent", agent);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        log.debug("Attempting to connect to " + query);

        InputStream in = conn.getInputStream();
        bufIn = new BufferedInputStream(in);

        StringBuilder sb = new StringBuilder();
        while (true) {
            int data = bufIn.read();
            if (data == -1) {
                break;
            } else {
                sb.append((char) data);
            }
        }
        String result = sb.toString();
        if (result.length() == 0) {
            log.info("no update needed");
            set(null, null);
        } else {
            log.warn("UPGRADE AVAILABLE:" + result);
            set(result, null);
        }
    } catch (UnknownHostException uhe) {
        log.error("Unknown host:" + url);
        set(null, uhe);
    } catch (IOException ioe) {
        log.error(String.format("Error reading from url: %s \"%s\"", query, ioe.getMessage()));
        set(null, ioe);
    } catch (Exception ex) {
        log.error("Unknown exception thrown on UpgradeCheck", ex);
        set(null, ex);
    } finally {
        Utils.closeQuietly(bufIn);
    }
}