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:de.unigoettingen.sub.commons.util.stream.StreamUtils.java

/************************************************************************************
 * get {@link InputStream} from given URL using a basis path and proxy informations
 * //  w  ww  . j av  a 2  s . c o  m
 * @param url the url from where to get the {@link InputStream}
 * @param basepath the basispath
 * @param httpproxyhost the host for proxy
 * @param httpproxyport the port for proxy
 * @param httpproxyusername the username for the proxy
 * @param httpproxypassword the password for the proxy
 * @return {@link InputStream} for url
 * @throws IOException
 ************************************************************************************/
public static InputStream getInputStreamFromUrl(URL url, String basepath, String httpproxyhost,
        String httpproxyport, String httpproxyusername, String httpproxypassword) throws IOException {
    InputStream inStream = null;

    if (url.getProtocol().equalsIgnoreCase("http")) {
        if (httpproxyhost != null) {
            Properties properties = System.getProperties();
            properties.put("http.proxyHost", httpproxyhost);
            if (httpproxyport != null) {
                properties.put("http.proxyPort", httpproxyport);
            } else {
                properties.put("http.proxyPort", "80");
            }
        }
        URLConnection con = url.openConnection();
        if (httpproxyusername != null) {
            String login = httpproxyusername + ":" + httpproxypassword;
            String encodedLogin = new String(Base64.encodeBase64(login.getBytes()));
            con.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
        }
        inStream = con.getInputStream();
    } else if (url.getProtocol().equalsIgnoreCase("file")) {
        int size = url.openConnection().getContentLength();
        Integer maxFileLength = ContentServerConfiguration.getInstance().getMaxFileLength();

        if (maxFileLength != 0 && size > maxFileLength) {
            // System.out.println("File " + url.getFile() + " is too large (" + size + "/" + maxFileLength + ")");
            return getInputStreamFromUrl(new URL(ContentServerConfiguration.getInstance().getErrorFile()));
        }
        String filepath = url.getFile();

        filepath = URLDecoder.decode(filepath, System.getProperty("file.encoding"));

        File f = new File(filepath);
        if (!f.isFile()) {
            // try for a file with different suffix case
            int suffixIndex = filepath.lastIndexOf('.');
            f = new File(filepath.substring(0, suffixIndex) + filepath.substring(suffixIndex).toLowerCase());
            if (!f.isFile()) {
                f = new File(
                        filepath.substring(0, suffixIndex) + filepath.substring(suffixIndex).toUpperCase());
            }
            // search all files in this directory for this case-insensitive name
            if (!f.isFile()) {
                File[] files = f.getParentFile().listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.getName().compareToIgnoreCase(f.getName()) == 0) {
                            f = file;
                            break;
                        }
                    }
                }
            }
        }
        inStream = new FileInputStream(f);

    } else if (url.getProtocol().length() == 0) {
        String filepath = url.getFile();
        // we just have the relative path, need to find the absolute path
        String path = basepath + filepath;

        // call this method again
        URL completeurl = new URL(path);
        inStream = getInputStreamFromUrl(completeurl);
    }

    return inStream;
}

From source file:modelcreation.ModelCreation.java

public static Team[] getTeams(int seasonId) {
    String response = "";
    try {/*from  w  w w  . j a  v  a 2s.c o  m*/
        URL api = new URL("http://api.football-data.org/v1/soccerseasons/" + seasonId + "/teams");
        URLConnection connection = api.openConnection();
        connection.setRequestProperty("X-Auth-Token", TOKEN);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response += inputLine;
        }
        in.close();
    } catch (MalformedURLException ex) {
        Logger.getLogger(ModelCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ModelCreation.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (response.isEmpty()) {
        System.out.println("Response is empty!");
        return null;
    }

    Team[] teams = Team.createTeams(response);

    return teams;
}

From source file:modelcreation.ModelCreation.java

public static Team[] getTeamsWithFixtures(int seasonId, int seasonYear) {
    String response = "";
    try {/*  w w  w  .j av  a2  s .  c  o  m*/
        URL api = new URL("http://api.football-data.org/v1/soccerseasons/" + seasonId + "/teams");
        URLConnection connection = api.openConnection();
        connection.setRequestProperty("X-Auth-Token", TOKEN);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response += inputLine;
        }
        in.close();
    } catch (MalformedURLException ex) {
        Logger.getLogger(ModelCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ModelCreation.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (response.isEmpty()) {
        System.out.println("Response is empty!");
        return null;
    }

    Team[] teams = Team.createTeamsWithFixtures(response, seasonYear);

    return teams;
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static <T extends RestObject> T getRestObject(Class<T> restObject, String url)
        throws RestfulAPIException {
    InputStream stream = null;/*  ww  w .ja  v a2 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();
        T result = mapper.readValue(stream, restObject);
        if (result.hasError()) {
            throw new RestfulAPIException("Error in json response: " + result.getError());
        }

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

From source file:com.omertron.themoviedbapi.tools.WebBrowser.java

private static void sendHeader(URLConnection cnx) {
    populateBrowserProperties();//from   w w  w.ja v  a 2s.co  m

    // send browser properties
    for (Map.Entry<String, String> browserProperty : BROWSER_PROPERTIES.entrySet()) {
        cnx.setRequestProperty(browserProperty.getKey(), browserProperty.getValue());
    }
    // send cookies
    String cookieHeader = createCookieHeader(cnx);
    if (!cookieHeader.isEmpty()) {
        cnx.setRequestProperty("Cookie", cookieHeader);
    }
}

From source file:org.wso2.carbon.connector.common.ConnectorIntegrationUtil.java

public static OMElement sendXMLRequest(String addUrl, String query)
        throws MalformedURLException, IOException, XMLStreamException {

    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);// w w  w  .  ja  va 2 s .  c om
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    InputStream response;

    if (httpConn.getResponseCode() >= 400) {
        response = httpConn.getErrorStream();
    } else {
        response = connection.getInputStream();
    }

    String out = "{}";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }

        if (!sb.toString().trim().isEmpty()) {
            out = sb.toString();
        }
    }

    OMElement omElement = AXIOMUtil.stringToOM(out);

    return omElement;

}

From source file:org.wso2.connector.integration.bloggerV3.ConnectorIntegrationUtil.java

public static JSONObject sendRequestWithAcceptHeader(String addUrl, String query)
        throws IOException, JSONException {

    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);//from www. ja va  2  s .  c  o m
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    InputStream response;

    if (httpConn.getResponseCode() >= 400) {
        response = httpConn.getErrorStream();
    } else {
        response = connection.getInputStream();
    }

    String out = "{}";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }

        if (!sb.toString().trim().isEmpty()) {
            out = sb.toString();
        }
    }

    JSONObject jsonObject = new JSONObject(out);

    return jsonObject;
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static HashMap<String, Minecraft> getMinecraftVersions() throws RestfulAPIException {
    InputStream stream = null;//w  ww  .j  a  va  2  s.  co m
    try {
        URLConnection conn = new URL(getMinecraftVersionURL()).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();
        HashMap<String, Minecraft> versions = mapper.readValue(stream,
                new TypeReference<Map<String, Minecraft>>() {
                });

        for (Minecraft result : versions.values()) {
            if (result.hasError()) {
                throw new RestfulAPIException("Error in json response: " + result.getError());
            }
        }

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.spoutcraft.launcher.rest.RestAPI.java

public static List<Article> getNews() throws RestfulAPIException {
    InputStream stream = null;//from w  w w .  j  a v a2 s .com
    try {
        URLConnection conn = new URL(getPlatformAPI() + "news/").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();
        List<Article> versions = mapper.readValue(stream, new TypeReference<List<Article>>() {
        });

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

        return versions;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + getMinecraftVersionURL() + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + getMinecraftVersionURL() + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:info.magnolia.cms.exchange.simple.Transporter.java

/**
 * http form multipart form post//  www . j av  a  2  s.  com
 * @param connection
 * @param activationContent
 * @throws ExchangeException
 */
public static void transport(URLConnection connection, ActivationContent activationContent)
        throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
        connection.setRequestProperty("Cache-Control", "no-cache");

        outStream = new DataOutputStream(connection.getOutputStream());
        outStream.writeBytes("--" + BOUNDARY + "\r\n");

        // set all resources from activationContent
        Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
        while (fileNameIterator.hasNext()) {
            String fileName = (String) fileNameIterator.next();
            fis = new FileInputStream(activationContent.getFile(fileName));
            outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\""
                    + fileName + "\"\r\n");
            outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
            while (true) {
                synchronized (buffer) {
                    int amountRead = fis.read(buffer);
                    if (amountRead == -1) {
                        break;
                    }
                    outStream.write(buffer, 0, amountRead);
                }
            }
            fis.close();
            outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
        }
        outStream.flush();
        outStream.close();

        log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
        throw new ExchangeException(
                "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
    }

}