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:com.n1t3slay3r.empirecraft.main.Update.java

/**
 * Query the API to find the latest approved file's details.
 *//*from   w  w w.  j  av a 2s . co  m*/
public void query() {
    URL url;

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

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

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // 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);

            if (playername != null) {
                Bukkit.getPlayer(UUID.fromString(playername))
                        .sendMessage(ChatColor.YELLOW + "The latest version of " + ChatColor.GOLD
                                + versionFileName + ChatColor.YELLOW + " is " + ChatColor.GOLD + versionName
                                + ChatColor.YELLOW + ", a " + ChatColor.GOLD + versionType.toUpperCase()
                                + ChatColor.YELLOW + " for " + ChatColor.GOLD + versionGameVersion
                                + ChatColor.YELLOW + ", available at: " + ChatColor.GOLD + versionLink);
            } else {
                System.out.println("The latest version of " + versionFileName + " is " + versionName + ", a "
                        + versionType.toUpperCase() + " for " + versionGameVersion + ", available at: "
                        + versionLink);
            }
        }
    } catch (IOException e) {
    }
}

From source file:org.voyanttools.trombone.input.source.UriInputSource.java

private URLConnection getURLConnection(URI uri, int readTimeoutMilliseconds, int connectTimeoutMilliseconds)
        throws IOException {
    URLConnection c;
    try {//from   ww w.  ja  v  a2s. c om
        c = uri.toURL().openConnection();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Attempt to use a malformed URL: " + uri, e);
    }
    c.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Trombone)");
    c.setReadTimeout(readTimeoutMilliseconds);
    c.setConnectTimeout(connectTimeoutMilliseconds);
    return c;
}

From source file:de.matzefratze123.heavyspleef.util.Updater.java

public void query() {
    URL url;//from  w w w  .  j  a v a  2 s .c o m

    try {
        url = new URL(API_HOST + API_QUERY + PROJECT_ID);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return;
    }

    try {
        URLConnection conn = url.openConnection();

        conn.setConnectTimeout(6000);
        conn.addRequestProperty("User-Agent", "HeavySpleef-Updater (by matzefratze123)");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String query = reader.readLine();

        JSONArray array = (JSONArray) JSONValue.parse(query);

        String version = null;

        if (array.size() > 0) {

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

            fileTitle = (String) latest.get(API_TITLE_VALUE);
            fileName = (String) latest.get(API_NAME_VALUE);
            downloadUrl = (String) latest.get(API_LINK_VALUE);

            String[] parts = fileTitle.split(" v");
            if (parts.length >= 2) {
                version = parts[1];
            }

            checkVersions(version);
            done = true;
        }
    } catch (IOException e) {
        Logger.severe("Failed querying the curseforge api: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:de.mango.business.GoogleSearchProvider.java

public Vector<String> search(String query, int count, int page) {
    Vector<String> results = new Vector<String>();
    // Prepare the query
    try {//from   ww w .  j  av a 2  s.  co m
        query = "http://ajax.googleapis.com/ajax/services/search/images?" + GoogleSearchProvider.searchArguments
                + this.hostLanguage + "&q="
                + URLEncoder.encode(
                        GoogleSearchProvider.restrictToOpenClipart ? query + GoogleSearchProvider.openClipart
                                : query,
                        "UTF-8")
                + "&start=";
    } catch (UnsupportedEncodingException e) {
        if (DEBUG) {
            Log.w(TAG, "Unsupported Encoding Exception:" + e.getMessage());
            Log.w(TAG, Log.getStackTraceString(e));
        }
        return results;
    }

    // start argument to pass to google
    int firstindex = count * page;
    // count of results to skip before adding them to the result array
    int skip = 0;
    // start indices > 56 are skipped by Google, so we
    // ask for results from 56, but skip the unwanted $skip indices
    if (firstindex > 63)
        return results;
    if (firstindex > 56) {
        skip = firstindex - 56;
        firstindex = 56;
    }

    boolean readMore = true; // do we need more queries and are they
    // possible?
    while (readMore) {
        // add start index to the query
        String currentQuery = query + firstindex;
        if (DEBUG)
            Log.d(TAG, "Searching: " + currentQuery);
        try {
            // prepare the connection
            URL url = new URL(currentQuery);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", GoogleSearchProvider.refererUrl);

            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.connect();

            // receive the results
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            // parse the results
            JSONObject json = new JSONObject(builder.toString());
            int responseStatus = json.getInt("responseStatus");
            if (responseStatus == 200)// successful search
            {
                json = json.getJSONObject("responseData");
                JSONArray res = json.getJSONArray("results");
                if (res.length() == 0)
                    return results;
                String s;
                int limit = Math.min(res.length(), count - results.size() + skip);
                for (int i = skip; i < limit; i++) {
                    s = res.getJSONObject(i).getString("unescapedUrl");
                    if (s != null)
                        results.addElement(s);
                }
                // see if there are "more Results"
                JSONObject cursor = json.getJSONObject("cursor");
                JSONArray pages = cursor.getJSONArray("pages");
                int pageCount = pages.length();
                int currentPageIndex = cursor.getInt("currentPageIndex");
                this.moreResults = readMore = (pageCount - 1) > currentPageIndex;
            } else {
                if (DEBUG)
                    Log.w(TAG, "Goole Search Error (Code " + responseStatus + "):"
                            + json.getString("responseDetails"));
                this.moreResults = readMore = false;// prevent for (;;) loop
                // on errors
            }
        } catch (MalformedURLException e) {
            if (DEBUG) {
                Log.w(TAG, "MalformedURLException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (IOException e) {
            if (DEBUG) {
                Log.w(TAG, "IOException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (JSONException e) {
            if (DEBUG) {
                Log.w(TAG, "JSONException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        }

        // read more only if we can read more AND want to have more
        readMore = readMore && results.size() < count;
        if (readMore) {
            firstindex += 8;
            if (firstindex > 56)// the last pages always need to start
            // querying at index 56 (or google returns
            // errors)
            {
                skip = firstindex - 56;
                firstindex = 56;
            }
        }
    }
    return results;
}

From source file:com.wasteofplastic.acidisland.Update.java

/**
 * Query the API to find the latest approved file's details.
 * /*from   ww  w  .j  ava2 s .c o  m*/
 * @return true if successful
 */
public boolean 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 false;
    }

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

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ASkyBlockAcidIsland Update Checker");

        // 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
            versionName = (String) latest.get(API_NAME_VALUE);

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

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

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

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

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

        e.printStackTrace();
        return false;
    }
}

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

protected URLConnection createConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("User-Agent", "Hockey/Android");
    connection.setRequestProperty("connection", "close");
    return connection;
}

From source file:io.druid.segment.realtime.firehose.HttpFirehoseFactory.java

@Override
protected InputStream openObjectStream(URI object, long start) throws IOException {
    if (supportContentRange) {
        final URLConnection connection = object.toURL().openConnection();
        // Set header for range request.
        // Since we need to set only the start offset, the header is "bytes=<range-start>-".
        // See https://tools.ietf.org/html/rfc7233#section-2.1
        connection.addRequestProperty(HttpHeaders.RANGE, StringUtils.format("bytes=%d-", start));
        return connection.getInputStream();
    } else {//  w ww  .jav a2 s .  c om
        log.warn(
                "Since the input source doesn't support range requests, the object input stream is opened from the start and "
                        + "then skipped. This may make the ingestion speed slower. Consider enabling prefetch if you see this message"
                        + " a lot.");
        final InputStream in = openObjectStream(object);
        in.skip(start);
        return in;
    }
}

From source file:BRHInit.java

public JSONObject json_rpc(String method, JSONArray params) throws Exception {
    URLConnection conn = rpc_url.openConnection();
    if (cookie != null)
        conn.addRequestProperty("cookie", cookie);

    JSONObject request = new JSONObject();

    request.put("id", false);
    request.put("method", method);
    request.put("params", params);

    conn.setDoOutput(true);//from   w  ww.  ja  va 2s.  com
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    try {
        wr.write(request.toString());
        wr.flush();
    } finally {
        wr.close();
    }

    // Get the response
    InputStreamReader rd = new InputStreamReader(conn.getInputStream());
    try {
        JSONTokener tokener = new JSONTokener(rd);
        return (JSONObject) tokener.nextValue();
    } finally {
        rd.close();
    }
}

From source file:com.gmail.bleedobsidian.areaprotect.Updater.java

/**
 * Query ServerMods API for project variables.
 * /*from  ww  w  . j  a  v a  2s  .  com*/
 * @return If successful or not.
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

From source file:org.apache.jsp.fileUploader_jsp.java

public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie)
        CookieHandler.setDefault(cm);
    try {/* w  w w . jav  a 2  s.  c om*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        URLConnection urlConnection = url.openConnection();

        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        } else if (DEBUG_MODE)
            System.out.println("Infinit.e Cookie Value is Null");
        IOUtils.copy(urlConnection.getInputStream(), output);
        String newCookie = getConnectionInfiniteCookie(urlConnection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }

        String toReturn = output.toString();
        output.close();
        return toReturn;
    } catch (IOException e) {
        return null;
    }
}