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:org.betaconceptframework.astroboa.engine.jcr.util.BinaryChannelUtils.java

public void loadContentFromExternalLocation(Context context, BinaryChannel binaryChannel) {

    String externalLocationOfTheContent = ((BinaryChannelImpl) binaryChannel).getExternalLocationOfTheContent();

    if (!binaryChannel.isNewContentLoaded() && StringUtils.isNotBlank(externalLocationOfTheContent)) {

        //Check context first
        byte[] content = context.getBinaryContentForKey(externalLocationOfTheContent);

        //try to download
        if (content == null) {
            InputStream inputStream = null;
            try {
                URL urlResource = new URL(externalLocationOfTheContent);

                if (Astroboa_Resource_Api_Pattern.matcher(externalLocationOfTheContent).matches()
                        && context.getImportConfiguration() != null
                        && context.getImportConfiguration()
                                .credentialsOfUserWhoHasAccessToBinaryContent() != null
                        && context.getImportConfiguration().credentialsOfUserWhoHasAccessToBinaryContent()
                                .getUsername() != null
                        && context.getImportConfiguration().credentialsOfUserWhoHasAccessToBinaryContent()
                                .getPassword() != null) {

                    String username = context.getImportConfiguration()
                            .credentialsOfUserWhoHasAccessToBinaryContent().getUsername();
                    String password = context.getImportConfiguration()
                            .credentialsOfUserWhoHasAccessToBinaryContent().getPassword();

                    URLConnection uc = urlResource.openConnection();
                    uc.setRequestProperty("Authorization", "Basic "
                            + new String(Base64.encodeBase64(((username + ":" + password).getBytes()))));
                    inputStream = (InputStream) uc.getInputStream();

                } else {
                    inputStream = urlResource.openStream();
                }/*  w w w.  j  a v  a  2  s .  c o  m*/

                binaryChannel.setContent(IOUtils.toByteArray(inputStream));

            } catch (Throwable e) {
                //Log exception but continue with unmarshaling
                //BinaryChannle will be created without content
                logger.warn("Invalid external location " + externalLocationOfTheContent
                        + " of the content for binary channel " + binaryChannel.getName(), e);
            } finally {
                if (inputStream != null) {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        } else {
            binaryChannel.setContent(content);
        }
    }
}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousImporter.java

/**
 * Method opens a connection and parses the retrieved InputStream with a JAXP parser.
 * @return The from the parse call returned Document Object
 * @throws IOException//  w ww.  j a  v  a 2s  . c om
 */
private Document getDocument() throws IOException {

    final URLConnection connection = apiURL.openConnection();
    connection.setRequestProperty(HEADER_USER_AGENT, userAgent);
    connection.setRequestProperty(HEADER_AUTHORIZATION, encodeForAuthorization());
    final InputStream inputStream = connection.getInputStream();

    // Get a JAXP parser factory object
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want 
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object

    final DocumentBuilder parser;
    try {
        parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }

    // Tell the parser how to handle errors.  Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException e) {
            log.warn(e);
        }

        public void error(SAXParseException e) {
            log.error(e);
        }

        public void fatalError(SAXParseException e) throws SAXException {
            log.fatal(e);
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file.  
    // This call returns a Document object. 

    final Document document;
    try {
        document = parser.parse(inputStream);
    } catch (SAXException e) {
        throw new IOException(e);
    }

    inputStream.close();

    return document;

}

From source file:dlauncher.dialogs.Login.java

private void login_write(String UserName, String Password) {
    Logger.getGlobal().info("Started login process");
    Logger.getGlobal().info("Writing login data..");
    try {// w  ww  .  ja v a  2  s . c o  m
        url = new URL("http://authserver.mojang.com/authenticate");

        final URLConnection con = url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json");
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()))) {
            writer.write("{\n" + "  \"agent\": {" + "    \"name\": \"Minecraft\"," + "    \"version\": 1" + "\n"
                    + "  },\n" + "  \"username\": \"" + UserName + "\",\n" + "\n" + "  \"password\": \""
                    + Password + "\",\n" + "}");

            writer.close();
        }
        Logger.getGlobal().info("Succesful written login data");
    } catch (MalformedURLException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    } catch (IOException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    }
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {// w ww.j a  v  a2s  .c  o  m
        String data = new String();
        Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}

From source file:net.solarnetwork.node.support.JsonHttpClientSupport.java

/**
 * Perform a JSON HTTP request.//ww w.  j a va2 s .  c  o m
 * 
 * @param url
 *        the URL to make the request to
 * @param method
 *        the HTTP method, e.g. {@link HttpClientSupport#HTTP_METHOD_GET}
 * @param data
 *        the optional data to marshall to JSON and upload as the request
 *        content
 * @return the InputStream for the HTTP response
 * @throws IOException
 *         if any IO error occurs
 */
protected final InputStream doJson(String url, String method, Object data) throws IOException {
    URLConnection conn = getURLConnection(url, method, JSON_MIME_TYPE);
    if (data != null) {
        conn.setRequestProperty("Content-Type", JSON_MIME_TYPE + ";charset=UTF-8");
        if (compress) {
            conn.setRequestProperty("Content-Encoding", "gzip");
        }
        OutputStream out = conn.getOutputStream();
        if (compress) {
            out = new GZIPOutputStream(out);
        }

        if (log.isDebugEnabled()) {
            log.debug("Posting JSON data: {}",
                    objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data));
        }
        objectMapper.writeValue(out, data);
        out.flush();
        out.close();
    }

    return getInputStreamFromURLConnection(conn);
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendGETRequest(String urlString) throws Exception {
    try {//from   ww  w.j ava2 s  . c o  m
        URL url = new URL(urlString);
        URLConnection connection = (URLConnection) url.openConnection();
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("apikey", _apiKey);

        HttpURLConnection http_conn = (HttpURLConnection) connection;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;
    } catch (Exception e) {
        throw e;
    }
}

From source file:ch.entwine.weblounge.maven.MyGengoI18nImport.java

private URLConnection getMyGengoConn() {
    // Request MyGengo i18n file
    URLConnection conn;
    try {//from  w ww  . j av  a2 s .c  om
        conn = myGengoUrl.openConnection();
        if (StringUtils.isNotBlank(myGengoUsername) && StringUtils.isNotBlank(myGengoPassword))
            conn.setRequestProperty("Authorization", "Basic "
                    + (new Base64()).encode((myGengoUsername + ":" + myGengoPassword).getBytes()).toString());
    } catch (IOException e) {
        log.error("Error getting zip file from myGengo.");
        return null;
    }
    return conn;
}

From source file:com.kaloer.yummly.Yummly.java

/**
 * Performs the actual HTTP-request.//from w w  w  . j a  va2  s.c o  m
 * 
 * @param appendedUrl
 *            The specific URL-extension of the api.
 * @param parameters
 *            The url parameters.
 * @return An inputstream of the response.
 * @throws IOException
 *             Thrown if network errors occur.
 */
private InputStream performRequest(String appendedUrl, ArrayList<Parameter> parameters) throws IOException {
    StringBuilder paramString = new StringBuilder();
    // Set parameters.
    if (parameters != null) {
        boolean firstLoop = true;
        for (Parameter param : parameters) {
            if (firstLoop) {
                paramString.append("?");
                firstLoop = false;
            } else {
                paramString.append("&");
            }
            paramString.append(param.key);
            paramString.append("=");
            paramString.append(param.value);
        }
    }

    URL endpoint = new URL(BASE_URL + appendedUrl + paramString);
    System.out.println(endpoint);
    URLConnection urlCon = endpoint.openConnection();
    // Add header fields.
    urlCon.setRequestProperty("X-Yummly-App-ID", mAppId);
    urlCon.setRequestProperty("X-Yummly-App-Key", mAppKey);

    return urlCon.getInputStream();
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java

private void fetch(File aTarget, DataPackage... aPackages) throws IOException {
    // First validate if local copies are still up-to-date
    boolean reload = false;
    packageValidationLoop: for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        if (!cachedFile.exists()) {
            continue;
        }//w  w  w  .  j  av  a  2 s . c  o  m

        if (pack.getSha1() != null) {
            String actual = getDigest(cachedFile, "SHA1");
            if (!pack.getSha1().equals(actual)) {
                LOG.info("Local SHA1 hash mismatch on [" + cachedFile + "] - expected [" + pack.getSha1()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local SHA1 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

        if (pack.getMd5() != null) {
            String actual = getDigest(cachedFile, "MD5");
            if (!pack.getMd5().equals(actual)) {
                LOG.info("Local MD5 hash mismatch on [" + cachedFile + "] - expected [" + pack.getMd5()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local MD5 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

    }

    // If any of the packages are outdated, clear the cache and download again
    if (reload) {
        LOG.info("Clearing local cache for [" + aTarget + "]");
        FileUtils.deleteQuietly(aTarget);
    }

    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());

        if (cachedFile.exists()) {
            continue;
        }

        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        cachedFile.getParentFile().mkdirs();
        URL source = new URL(pack.getUrl());

        LOG.info("Fetching [" + cachedFile + "]");

        URLConnection connection = source.openConnection();
        connection.setRequestProperty("User-Agent", "Java");

        try (InputStream is = connection.getInputStream()) {
            DigestInputStream md5Filter = new DigestInputStream(is, md5);
            DigestInputStream sha1Filter = new DigestInputStream(md5Filter, sha1);
            FileUtils.copyInputStreamToFile(sha1Filter, cachedFile);

            if (pack.getMd5() != null) {
                String md5Hex = new String(Hex.encodeHex(md5Filter.getMessageDigest().digest()));
                if (!pack.getMd5().equals(md5Hex)) {
                    String message = "MD5 mismatch. Expected [" + pack.getMd5() + "] but got [" + md5Hex + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }

            if (pack.getSha1() != null) {
                String sha1Hex = new String(Hex.encodeHex(sha1Filter.getMessageDigest().digest()));
                if (!pack.getSha1().equals(sha1Hex)) {
                    String message = "SHA1 mismatch. Expected [" + pack.getSha1() + "] but got [" + sha1Hex
                            + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }
        }
    }

    // Perform a post-fetch action such as unpacking
    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        File postActionCompleteMarker = new File(cachedFile.getPath() + ".postComplete");
        if (pack.getPostAction() != null && !postActionCompleteMarker.exists()) {
            try {
                pack.getPostAction().run(pack);
                FileUtils.touch(postActionCompleteMarker);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java

@Override
public List<Album> getAlbumInfo(Album albumHelpInfo, File[] files) {
    if (albumHelpInfo == null || (albumHelpInfo.name == null && albumHelpInfo.author == null)
            || ((albumHelpInfo.name != null && albumHelpInfo.name.length() <= 0)
                    && (albumHelpInfo.author != null && albumHelpInfo.author.length() <= 0))) {
        return new ArrayList<Album>();
    }//from  w  ww.j ava  2  s .  c om

    String baseURL = "http://api.discogs.com/database/search?type=release";

    try {
        if (albumHelpInfo.name != null) {
            baseURL = baseURL + "&release_title=" + URLEncoder.encode(albumHelpInfo.name, "UTF-8") + "";
        }
        if (albumHelpInfo.author != null) {
            baseURL = baseURL + "&artist=" + URLEncoder.encode(albumHelpInfo.author, "UTF-8") + "";
        }

        URL url = new URL(baseURL);
        Proxy proxy = getProxy();
        URLConnection uc = (proxy != null ? url.openConnection(proxy) : url.openConnection());
        uc.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/");

        ArrayList<Album> result = new ArrayList<Album>();

        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
        JsonParser jParser = jsonFactory.createParser(uc.getInputStream());
        while (jParser.nextToken() != null) {
            String fieldname = jParser.getCurrentName();
            if ("id".equals(fieldname)) {
                jParser.nextToken();
                String id = jParser.getText();
                // one second per petition allowed by discogs
                Thread.sleep(1000);

                Album album = getAlbum(id);

                result.add(album);
            }

        }
        return result;
    } catch (Exception e) {
        log.error("failed!", e);
    }

    return null;
}