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:com.orthancserver.OrthancConnection.java

private static InputStream OpenUrl(String urlString, String authentication) throws IOException {
    try {//from  w  w  w .  j a  va 2  s .  c  o m
        URL url = new URL(urlString);
        // http://blogs.deepal.org/2008/01/sending-basic-authentication-using-url.html
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("Authorization", "Basic " + authentication);
        return uc.getInputStream();
    } catch (ConnectException e) {
        throw new IOException();
    }
}

From source file:sh.isaac.provider.sync.git.gitblit.utils.ConnectionUtils.java

/**
 * Open read connection./* w  w  w.  j  a  va 2 s .co  m*/
 *
 * @param url the url
 * @param username the username
 * @param password the password
 * @return the URL connection
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static URLConnection openReadConnection(String url, String username, char[] password)
        throws IOException {
    final URLConnection conn = openConnection(url, username, password);

    conn.setRequestProperty("Accept-Charset", ConnectionUtils.CHARSET);
    return conn;
}

From source file:net.dv8tion.discord.util.GoogleSearch.java

public static List<SearchResult> performSearch(String engineId, String terms, int requiredResultsCount) {
    try {/*from w  w  w  . j a v a 2s.  c om*/
        if (GOOGLE_API_KEY == null)
            throw new IllegalStateException(
                    "Google API Key is null, Cannot preform google search without a key! Set one in the settings!");
        if (engineId == null || engineId.isEmpty())
            throw new IllegalArgumentException("Google Custom Search Engine id cannot be null or empty!");

        LocalDateTime currentTime = LocalDateTime.now();
        if (currentTime.isAfter(dayStartTime.plusDays(1))) {
            dayStartTime = currentTime;
            currentGoogleUsage = 1;
        } else if (currentGoogleUsage >= 80) {
            throw new IllegalStateException("Google usage has reached the premature security cap of 80");
        }

        terms = terms.replace(" ", "%20");
        String searchUrl = String.format(GOOGLE_URL, engineId, GOOGLE_API_KEY, requiredResultsCount, terms);

        URL searchURL = new URL(searchUrl);
        URLConnection conn = searchURL.openConnection();
        currentGoogleUsage++;
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 " + randomName(10));
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            json.append(line).append("\n");
        }
        in.close();

        JSONArray jsonResults = new JSONObject(json.toString()).getJSONArray("items");
        List<SearchResult> results = new LinkedList<>();
        for (int i = 0; i < jsonResults.length(); i++) {
            results.add(SearchResult.fromGoogle(jsonResults.getJSONObject(i)));
        }
        return results;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.sf.jabref.logic.util.Version.java

/**
 * Grabs the latest release version from the JabRef GitHub repository
 *//*from w w w . j a  v  a  2 s  . c om*/
public static Version getLatestVersion() throws IOException {
    URLConnection connection = new URL(JABREF_GITHUB_URL).openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    JSONObject obj = new JSONObject(rd.readLine());
    return new Version(obj.getString("tag_name").replaceFirst("v", ""));
}

From source file:resources.XmlToAnime.java

private static InputStream getInput() {
    String username = "shigato";
    String password = "unlimited0";
    String authString = username + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    InputStream in = null;/*from   w  w  w .j a  v a  2 s.c  o  m*/

    try {
        URL url = new URL(sUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        urlConnection.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        urlConnection.setRequestProperty("Accept-Language", "en");
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36");
        in = urlConnection.getInputStream();
        String temp = InputStreamToString.getStringFromInputStream(in);
        temp = Replacer.replaceIllegalCharacters(temp);
        in = new ByteArrayInputStream(temp.getBytes(StandardCharsets.UTF_8));
        System.out.println();

        //            InputStreamReader isr = new InputStreamReader(in);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuilder sb = new StringBuilder();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                    sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        //            System.out.println(result);

    } catch (IOException e) {

    }
    return in;
}

From source file:net.technicpack.rest.RestObject.java

public static <T extends RestObject> T getRestObject(Class<T> restObject, String url)
        throws RestfulAPIException {
    InputStream stream = null;/* w  ww  .  j  av  a  2  s. com*/
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        String data = IOUtils.toString(stream, Charsets.UTF_8);
        T result = gson.fromJson(data, restObject);

        if (result == null) {
            throw new RestfulAPIException("Unable to access URL [" + url + "]");
        }

        if (result.hasError()) {
            throw new RestfulAPIException("Error in response: " + result.getError());
        }

        return result;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
    } catch (MalformedURLException e) {
        throw new RestfulAPIException("Invalid URL [" + url + "]", e);
    } catch (JsonParseException e) {
        throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:net.technicpack.rest.RestObject.java

public static <T> List<T> getRestArray(Class<T> restObject, String url) throws RestfulAPIException {
    InputStream stream = null;/*w  w w .  j a  va2s .  c  om*/
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        String data = IOUtils.toString(stream, Charsets.UTF_8);

        JsonElement response = gson.fromJson(data, JsonElement.class);

        if (response == null || !response.isJsonArray()) {
            if (response.isJsonObject() && response.getAsJsonObject().has("error"))
                throw new RestfulAPIException("Error in response: " + response.getAsJsonObject().get("error"));
            else
                throw new RestfulAPIException("Unable to access URL [" + url + "]");
        }

        JsonArray array = response.getAsJsonArray();
        List<T> result = new ArrayList<T>(array.size());

        for (JsonElement element : array) {
            if (element.isJsonObject())
                result.add(gson.fromJson(element.getAsJsonObject(), restObject));
            else
                result.add(gson.fromJson(element.getAsString(), restObject));
        }

        return result;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
    } catch (MalformedURLException e) {
        throw new RestfulAPIException("Invalid URL [" + url + "]", e);
    } catch (JsonParseException e) {
        throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.anyframe.oden.bundle.auth.AuthTest.java

private static URLConnection init(String url) throws MalformedURLException, IOException {
    URLConnection con = new URL(url).openConnection();
    con.setUseCaches(false);/*from w ww.  j av  a2s .  c o  m*/
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setConnectTimeout(TIMEOUT);
    con.setRequestProperty("Authorization", "Basic " + encode("oden", "oden0"));
    return con;
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String google(String s) {
    try {//from   ww w .java 2  s  .  c  o  m
        String temp = String.format("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s",
                URLEncoder.encode(s, "UTF-8"));
        URL u = new URL(temp);
        URLConnection c = u.openConnection();
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17");
        BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
        String json = "";
        String tmp;
        while ((tmp = in.readLine()) != null) {
            json += tmp + "\n";
        }
        in.close();
        JsonElement jelement = new JsonParser().parse(json);
        JsonObject output = jelement.getAsJsonObject();
        output = output.getAsJsonObject("responseData").getAsJsonArray("results").get(0).getAsJsonObject();

        String title = StringEscapeUtils.unescapeJava(StringEscapeUtils
                .unescapeHtml4(output.get("titleNoFormatting").toString().replaceAll("\"", "")));
        String content = StringEscapeUtils.unescapeJava(StringEscapeUtils.unescapeHtml4(output.get("content")
                .toString().replaceAll("\\s+", " ").replaceAll("\\<.*?>", "").replaceAll("\"", "")));
        String url = StringEscapeUtils.unescapeJava(output.get("url").toString().replaceAll("\"", ""));
        String result = String.format("Google: %s | %s | (%s)", title, content, url);
        if (result != null) {
            return result;
        } else {
            return "No results found for query " + s;
        }
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:cz.ceskaexpedice.k5.k5jaas.basic.K5LoginModule.java

public static URLConnection openConnection(String urlString, String user, String pass)
        throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    String userPassword = user + ":" + pass;
    String encoded = new String(Base64Coder.encode(userPassword.getBytes()));
    URLConnection uc = url.openConnection();
    uc.setReadTimeout(1000);/* w w  w . ja va 2 s  .c  o m*/
    uc.setConnectTimeout(1000);
    uc.setRequestProperty("Authorization", "Basic " + encoded);
    return uc;
}