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.fragzone.unrealmmo.bukkit.entities.npcs.NPCProfile.java

private static void addProperties(GameProfile profile, UUID id) {
    String uuid = id.toString().replaceAll("-", "");

    try {//from  w  ww .  j av a  2  s .c  o  m
        // Get the name from SwordPVP
        URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        uc.setDefaultUseCaches(false);
        uc.addRequestProperty("User-Agent", "Mozilla/5.0");
        uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
        uc.addRequestProperty("Pragma", "no-cache");

        // Parse it
        Scanner scanner = new Scanner(uc.getInputStream(), "UTF-8");
        String json = scanner.useDelimiter("\\A").next();
        scanner.close();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties");

        for (int i = 0; i < properties.size(); i++) {
            try {
                JSONObject property = (JSONObject) properties.get(i);
                String name = (String) property.get("name");
                String value = (String) property.get("value");
                String signature = property.containsKey("signature") ? (String) property.get("signature")
                        : null;
                if (signature != null) {
                    profile.getProperties().put(name, new Property(name, value, signature));
                } else {
                    profile.getProperties().put(name, new Property(value, name));
                }
            } catch (Exception e) {
                Bukkit.getLogger().log(Level.WARNING, "Failed to apply auth property", e);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.gallatinsystems.common.util.S3Util.java

public static URLConnection getConnection(String bucketName, String objectKey, String awsAccessKeyId,
        String awsAccessSecret) throws IOException {

    final String date = getDate();
    final String payload = String.format(GET_PAYLOAD, date, bucketName, objectKey);

    final String signature = MD5Util.generateHMAC(payload, awsAccessSecret);

    final URL url = new URL(String.format(S3_URL, bucketName, objectKey));
    final URLConnection conn = url.openConnection();

    conn.setConnectTimeout(CONNECTION_TIMEOUT);
    conn.setReadTimeout(CONNECTION_TIMEOUT);
    conn.addRequestProperty("Cache-Control", "no-cache,max-age=0");
    conn.setRequestProperty("Date", date);
    conn.setRequestProperty("Authorization", "AWS " + awsAccessKeyId + ":" + signature);

    return conn;//from w ww  .j  a v a  2 s . c o m
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http(String s) throws SQLException, IOException {

    String resp = "";
    final URL url = new URL(s);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setReadTimeout(60000);/*from w  w w  .  jav a 2 s.  c o m*/
    connection.addRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
    connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
    while (reader.hasNextLine()) {
        final String line = reader.nextLine();
        resp += line + "\n";
    }
    reader.close();

    return resp;
}

From source file:org.springframework.ide.eclipse.boot.core.initializr.InitializrServiceSpec.java

public static InitializrServiceSpec parseFrom(URLConnectionFactory urlConnectionFactory, URL url)
        throws IOException, Exception {
    URLConnection conn = null;
    InputStream input = null;//from  w ww  .j  a va 2  s . c o  m
    try {
        conn = urlConnectionFactory.createConnection(url);
        conn.addRequestProperty("Accept", JSON_CONTENT_TYPE_HEADER);
        conn.connect();
        input = conn.getInputStream();
        return parseFrom(input);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.sf.jabref.importer.fetcher.ACMPortalFetcher.java

private static Optional<BibEntry> downloadEntryBibTeX(String id, boolean downloadAbstract) {
    try {/*from   w  w  w.j  a  v a2s  .c o  m*/
        URL url = new URL(ACMPortalFetcher.START_URL + ACMPortalFetcher.BIBTEX_URL + id
                + ACMPortalFetcher.BIBTEX_URL_END);
        URLConnection connection = url.openConnection();

        // set user-agent to avoid being blocked as a crawler
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
        Collection<BibEntry> items = null;
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            items = BibtexParser.parse(in).getDatabase().getEntries();
        } catch (IOException e) {
            LOGGER.info("Download of BibTeX information from ACM Portal failed.", e);
        }
        if ((items == null) || items.isEmpty()) {
            return Optional.empty();
        }
        BibEntry entry = items.iterator().next();
        Thread.sleep(ACMPortalFetcher.WAIT_TIME);//wait between requests or you will be blocked by ACM

        // get abstract
        if (downloadAbstract) {
            URLDownload dl = new URLDownload(ACMPortalFetcher.START_URL + ACMPortalFetcher.ABSTRACT_URL + id);
            String page = dl.downloadToString(Globals.prefs.getDefaultEncoding());

            Matcher absM = ACMPortalFetcher.ABSTRACT_PATTERN.matcher(page);
            if (absM.find()) {
                entry.setField(FieldName.ABSTRACT, absM.group(1).trim());
            }
            Thread.sleep(ACMPortalFetcher.WAIT_TIME);//wait between requests or you will be blocked by ACM
        }

        return Optional.of(entry);
    } catch (NoSuchElementException e) {
        LOGGER.info("Bad BibTeX record read at: " + ACMPortalFetcher.BIBTEX_URL + id
                + ACMPortalFetcher.BIBTEX_URL_END, e);
    } catch (MalformedURLException e) {
        LOGGER.info("Malformed URL.", e);
    } catch (IOException e) {
        LOGGER.info("Cannot connect.", e);
    } catch (InterruptedException ignored) {
        // Ignored
    }
    return Optional.empty();
}

From source file:com.viettel.dms.download.DownloadFile.java

/**
 * Download file with urlConnection//from w ww  .ja v a  2 s . co  m
 * @author : BangHN
 * since : 1.0
 */
public static void downloadWithURLConnection(String url, File output, File tmpDir) {
    BufferedOutputStream os = null;
    BufferedInputStream is = null;
    File tmp = null;
    try {
        VTLog.i("Download ZIPFile", "Downloading url :" + url);

        tmp = File.createTempFile("download", ".tmp", tmpDir);
        URL urlDownload = new URL(url);
        URLConnection cn = urlDownload.openConnection();
        cn.addRequestProperty("session", HTTPClient.sessionID);
        cn.setConnectTimeout(CONNECT_TIMEOUT);
        cn.setReadTimeout(READ_TIMEOUT);
        cn.connect();
        is = new BufferedInputStream(cn.getInputStream());
        os = new BufferedOutputStream(new FileOutputStream(tmp));
        //cp nht dung lng tp tin request
        fileSize = cn.getContentLength();
        //vn c tr?ng hp khng c ContentLength
        if (fileSize < 0) {
            //mc nh = 4 MB
            fileSize = 4 * 1024 * 1024;
        }
        copyStream(is, os);
        tmp.renameTo(output);
        tmp = null;
    } catch (IOException e) {
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        throw new RuntimeException(e);
    } catch (Exception e) {
        VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e));
        ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false,
                TabletActionLogDTO.LOG_EXCEPTION);
        throw new RuntimeException(e);
    } finally {
        if (tmp != null) {
            try {
                tmp.delete();
                tmp = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (Exception ignore) {
                ;
            }
        }
        if (os != null) {
            try {
                os.close();
                os = null;
            } catch (Exception ignore) {
                ;
            }
        }
    }
}

From source file:io.bitsquare.common.util.Utilities.java

public static String readTextFileFromServer(String url, String userAgent) throws IOException {
    URLConnection connection = URI.create(url).toURL().openConnection();
    connection.setDoOutput(true);/*from   w ww . j a  v a 2 s  .c o m*/
    connection.setUseCaches(false);
    connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
    connection.addRequestProperty("User-Agent", userAgent);
    connection.connect();
    try (InputStream inputStream = connection.getInputStream()) {
        return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java

static void writeParameters(URLConnection c, Language sourceLang, Language targetLang, String... sources)
        throws IOException {
    StringBuilder b = new StringBuilder();
    b.append("langpair=").append(sourceLang.getCode()).append("|").append(targetLang.getCode());
    for (String s : sources) {
        b.append("&q=").append(URLEncoder.encode(s, "UTF-8"));
    }//from   w ww .j  a  v a  2  s  . c  o  m
    c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    c.getOutputStream().write(b.toString().getBytes("UTF-8"));
}

From source file:de.uzk.hki.da.at.AcceptanceTestHelper.java

private static String getFileAsHTMContent(String urlString) throws UnsupportedEncodingException, IOException {
    System.out.println("Fetch File from fedora: " + urlString);
    URL url = new URL(urlString);
    URLConnection urlc = url.openConnection();
    urlc.addRequestProperty("User-Agent", "Mozilla/5.0");
    StringBuilder ret = new StringBuilder();

    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
        ret.append(line);//ww  w.  j a va 2 s  . co  m
    }

    return ret.toString();
}

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Downloads a file from the network.//from www.  j  a  v  a  2s.  co  m
 * 
 * This function can fail in some cases (e.g. slow network), so if you really need the file, it
 * is recommended to do a few retries.
 * source: http://code.google.com/p/android/issues/detail?id=6066
 *
 * @param sourceUrl the url where the file is located
 * @param retries the number of retries in case the download fails
 * @return the stream if successful, else null
 */
public static byte[] downloadFile(String sourceUrl, int retries) {
    byte[] data = null;

    boolean successful = false;
    retries++; // add the first try
    do {
        try {
            retries--;
            URL url = new URL(sourceUrl);
            URLConnection urlConnection = url.openConnection();

            // set session cookie for authorization purposes (loading id pictures without being logged in is now [2011-07-04] disabled)
            Cookie cookie = Studentportal.getSportalClient().getSessionCookie();
            if (cookie != null) {
                urlConnection.addRequestProperty("Cookie", cookieHeaderString(cookie));
            }

            InputStream in = new BufferedInputStream(urlConnection.getInputStream(), 1024 * 32);
            data = streamToArray(in);
            in.close();
            successful = true;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // if the file doesn't exist, it's pointless to retry
            Log.d(TAG, "file does not exist: " + sourceUrl);
            retries = 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (!successful && retries > 0);

    return data;
}