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.taverna.component.profile.ComponentProfileImpl.java

private static void loadProfileFromURL(ComponentProfileImpl profile, URL source) {
    try {//from  w ww  . j  a v a 2 s .  c o  m
        URLConnection conn = source.openConnection();
        try {
            conn.addRequestProperty("Accept", "application/xml,*/*;q=0.1");
        } catch (Exception e) {
        }
        try (InputStream is = conn.getInputStream()) {
            profile.profileDoc = jaxbContext.createUnmarshaller().unmarshal(new StreamSource(is), Profile.class)
                    .getValue();
        }
    } catch (FileNotFoundException e) {
        profile.loaderException = e;
        logger.warn("URL not readable: " + source);
    } catch (Exception e) {
        profile.loaderException = e;
        logger.warn("Failed to load profile.", e);
    }
    synchronized (profile.lock) {
        profile.loaded = true;
        profile.lock.notifyAll();
    }
}

From source file:fr.free.movierenamer.utils.URIRequest.java

private static URLConnection openConnection(URI uri, RequestProperty... properties) throws IOException {
    boolean isHttpRequest = Proxy.Type.HTTP.name().equalsIgnoreCase(uri.getScheme());
    URLConnection connection;
    if (isHttpRequest && Settings.getInstance().isProxyIsOn()) {
        Settings settings = Settings.getInstance();
        Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(settings.getProxyUrl(), settings.getProxyPort()));
        connection = uri.toURL().openConnection(proxy);
    } else {//ww w  .  j  a  v  a  2  s .c  om
        connection = uri.toURL().openConnection();
    }

    if (isHttpRequest) {
        Settings settings = Settings.getInstance();
        connection.setReadTimeout(settings.getHttpRequestTimeOut() * 1000); // in ms
        //fake user agent ;)
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        connection.addRequestProperty("From", "googlebot(at)googlebot.com");
        connection.addRequestProperty("Accept", "*/*");
        String customUserAgent = settings.getHttpCustomUserAgent();
        if (customUserAgent != null && customUserAgent.length() > 0) {
            connection.addRequestProperty("User-Agent", customUserAgent);
        }
    }

    connection.addRequestProperty("Accept-Encoding", "gzip,deflate");
    connection.addRequestProperty("Accept-Charset", UTF + "," + ISO); // important for accents !

    if (properties != null) {
        for (RequestProperty property : properties) {
            connection.addRequestProperty(property.getKey(), property.getValue());
        }
    }

    return connection;
}

From source file:org.openflexo.toolbox.FileUtils.java

public static String createOrUpdateFileFromURL(URL url, File file, Map<String, String> headers) {
    long lastModified = 0;
    String fileContent = null;//from  w w w  .  ja v a  2 s  .c o m
    if (file.exists()) {
        lastModified = file.lastModified();
        try {
            fileContent = FileUtils.fileContents(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (url != null) {
        try {
            URLConnection c = url.openConnection();
            if (headers != null) {
                for (Map.Entry<String, String> h : headers.entrySet()) {
                    c.addRequestProperty(h.getKey(), h.getValue());
                }
            }
            if (c instanceof HttpURLConnection) {
                HttpURLConnection connection = (HttpURLConnection) c;
                connection.setIfModifiedSince(lastModified);
                connection.connect();
                if (connection.getResponseCode() == 200) {
                    fileContent = FileUtils.fileContents(connection.getInputStream(), "UTF-8");
                    FileUtils.saveToFile(file, fileContent);
                }
            } else {
                if (c.getDate() == 0 || c.getDate() > lastModified) {
                    fileContent = FileUtils.fileContents(c.getInputStream(), "UTF-8");
                    FileUtils.saveToFile(file, fileContent);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return fileContent;
}

From source file:org.jcodec.common.io.HttpRAInputStream.java

@Override
public void seek(long where) throws IOException {
    if (is != null)
        IOUtils.closeQuietly(is);//from   w  w  w.  ja va  2s .c  om
    URLConnection con = url.openConnection();
    con.addRequestProperty("range", where + "-" + length);
    is = con.getInputStream();
    pos = where;
}

From source file:logic.ZybezQuery.java

private String getJsonString() throws MalformedURLException, IOException {
    URL url = new URL(apiURL + itemRequested);
    URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

    //Put JSON data into String message
    String message = org.apache.commons.io.IOUtils.toString(in);
    return message;
}

From source file:org.intermine.api.mines.HttpRequester.java

@Override
public BufferedReader requestURL(final String urlString, final ContentType contentType) {
    BufferedReader reader = null;
    OutputStreamWriter writer = null;
    // TODO: when all friendly mines support mimetype formats then we can remove this.
    String suffix = "?format=" + contentType.getFormat();
    try {//w w w.j  a v  a2s . c  o m
        URL url = new URL(StringUtils.substringBefore(urlString, "?") + suffix);
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("Accept", contentType.getMimeType());
        conn.setConnectTimeout(timeout * 1000); // conn accepts millisecond timeout.
        if (urlString.contains("?")) {
            // POST
            String queryString = StringUtils.substringAfter(urlString, "?");
            conn.setDoOutput(true);
            writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(queryString);
            writer.flush();
            LOG.info("FriendlyMine URL (POST) " + urlString);
        }
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } catch (Exception e) {
        throw new RuntimeException("Unable to access " + urlString + " exception: " + e.getMessage());
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                LOG.error("Error sending POST request", e);
            }
        }
    }
    return reader;
}

From source file:logic.ZybezItemListing.java

private String getJsonString() throws MalformedURLException, IOException {
    URL url = new URL(apiURL + itemID);
    URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    //Put JSON data into String message
    String message = org.apache.commons.io.IOUtils.toString(in);
    return message;
}

From source file:org.marinemc.util.mojang.MojangUtils.java

private URLConnection getConnection(final URL url) throws Throwable {
    final URLConnection connection = url.openConnection();
    connection.addRequestProperty("User-Agent", "Mozilla/4.0");
    return connection;
}

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

public void execute(final InputHandler handler, Response response, String line)
        throws MalformedURLException, IOException, JSONException {
    String target = "en";
    String text = line;/*from   ww  w .j av  a 2  s .c  o m*/
    int offset;

    if ((offset = text.lastIndexOf(" into ")) > -1) {
        final String lang = text.substring(offset + 6);

        for (String[] pair : LANGUAGES) {
            if (pair[0].equalsIgnoreCase(lang)) {
                target = pair[1];
                text = text.substring(0, offset);
            }
        }
    }

    URL url = new URL("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=%7C" + target
            + "&q=" + URLEncoder.encode(text, Charset.defaultCharset().name()));
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer", "http://chris.smith.name/");

    String input;
    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"));
    }

    response.sendMessage(
            "that translates to \"" + json.getJSONObject("responseData").getString("translatedText") + "\"");
    response.addFollowup(new LanguageFollowup(json.getJSONObject("responseData")));
}

From source file:me.mast3rplan.phantombot.twitch.TwitchAPI.java

public JSONObject postObject(String url) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    connection.setUseCaches(false);/* www .jav a 2  s  .c o m*/
    connection.setDefaultUseCaches(false);
    connection.addRequestProperty(url, url);
    String content = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    return new JSONObject(content);
}