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.neuro4j.web.taglib.IncludeTagHandler.java

private void processIncludeRequest(String url, JspWriter out) {

    BufferedReader dis = null;/*from   ww  w .j a v a  2s  .  c o m*/
    try {

        URLConnection connection = new URL(url).openConnection();

        connection.setRequestProperty("Accept-Charset", charset);

        dis = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String inputLine;

        while ((inputLine = dis.readLine()) != null) {
            out.println(inputLine);
        }

    } catch (MalformedURLException me) {
        System.err.println("MalformedURLException: " + me);
    } catch (IOException ioe) {
        System.err.println("IOException: " + ioe);
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
            }
        }

    }

}

From source file:de.luhmer.owncloudnewsreader.async_tasks.GetImageThreaded.java

@Override
public void run() {
    try {//from   www.  j ava  2s  .  com
        File cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);

        DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(cont);
        Feed feed = dbConn.getFeedById(ThreadId);
        if (!cacheFile.isFile() || feed.getAvgColour() == null) {
            File dir = new File(rootPath);
            dir.mkdirs();
            cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);
            //cacheFile.createNewFile();

            /* Open a connection to that URL. */
            URLConnection urlConn = WEB_URL_TO_FILE.openConnection();

            urlConn.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");

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            //If the file is not empty
            if (baf.length() > 0) {
                bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());

                FileOutputStream fos = new FileOutputStream(cacheFile);
                fos.write(baf.toByteArray());
                fos.close();
            }
        }
        //return cacheFile.getPath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //return bmp;

    if (imageDownloadFinished != null)
        imageDownloadFinished.DownloadFinished(ThreadId, bmp);

    super.run();
}

From source file:uk.ac.cam.cl.dtg.util.locations.IPInfoDBLocationResolver.java

/**
 * Resolve location from third party service.
 * //  w  w w .  j  a  v  a2  s. com
 * @param url
 *            - fully qualified api request url.
 * @return the json response as a string.
 * @throws LocationServerException
 *             - if there is an error contacting the server.
 */
private String resolveFromServer(final URL url) throws LocationServerException {
    try {
        URLConnection ipInfoDBService = url.openConnection();
        ipInfoDBService.setRequestProperty("User-Agent", "IsaacPhysicsAPI");
        BufferedReader in = new BufferedReader(new InputStreamReader(ipInfoDBService.getInputStream()));
        String inputLine;
        StringBuilder jsonResponseBuilder = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            jsonResponseBuilder.append(inputLine);
        }

        in.close();

        return jsonResponseBuilder.toString();
    } catch (java.io.IOException e) {
        throw new LocationServerException(e.getMessage());
    }
}

From source file:com.sciamlab.util.HTTPClient.java

public String doGET(URL url, String user_agent) throws IOException {

    URLConnection yc = url.openConnection();
    if (user_agent != null && !"".equals(user_agent))
        yc.setRequestProperty("User-Agent", user_agent);
    String output = "";
    BufferedReader in = null;/* w  w  w.j a  v a2s  . c o  m*/
    try {
        in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        output = "";
        while ((inputLine = in.readLine()) != null)
            output += inputLine;

    } finally {
        if (in != null) {
            in.close();
        }
    }
    return output;
}

From source file:net.hgw4.hal.WebCamClientComm.java

/**
 * resets status of ring button rel/*from  w  w  w . j a  v  a  2 s. c  o m*/
 * @param port
 * @param status
 */
public void setPort(int port, int status) {
    try {
        String curPort = Integer.toString(port);
        String curStatus = new String();
        if (status == 1) {
            curStatus = "/"; //active
        } else {
            curStatus = "\\"; //inactive
        }
        URL url = new URL("http://" + ip + "/axis-cgi/io/output.cgi?action=" + curPort + ":" + curStatus);
        String userPassword = "<user>" + ":" + "<pass>";
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("Authorization", "Basic " + encoding);

        InputStream content = (InputStream) uc.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String str;
        str = in.readLine();
        in.close();

    } catch (MalformedURLException ex) {
        WebCamClientCommLogger.error(ex);
    } catch (IOException ex) {
        WebCamClientCommLogger.error(ex);
    }

}

From source file:net.hgw4.hal.WebCamClientComm.java

/**
 * check if input 1 is pressed == 1 ring button
 * @param port// w w w .j a  v a2 s.c o  m
 * @return
 */
public int checkPortStatus(int port) {

    try {
        String curport = Integer.toString(port);
        URL url = new URL("http://" + ip + "/axis-cgi/io/input.cgi?check=" + curport.toString()); //reply with input1=1 o 0
        String userPassword = "<user>" + ":" + "<passwd>";
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("Authorization", "Basic " + encoding);
        InputStream content = (InputStream) uc.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));

        String str;
        str = in.readLine();
        if (str.contentEquals("input1=1")) {
            return 1; //high
        } else if (str.contentEquals("input1=0")) {

            return 0; //low
        }
        in.close();

    } catch (MalformedURLException ex) {
        WebCamClientCommLogger.error(ex);
    } catch (IOException ex) {
        WebCamClientCommLogger.error(ex);
    }
    return -1;
}

From source file:fi.okm.mpass.idp.authn.impl.OAuth2Identity.java

@Override
public Subject getSubject(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    try {//from   w w w. ja v  a  2 s  .c  o  m
        TokenRequest request = getTokenRequest(httpRequest);
        if (request == null) {
            log.debug("User is not authenticated yet");
            log.trace("Leaving");
            return null;
        }
        TokenResponse tokenResponse = TokenResponse.parse(request.toHTTPRequest().send());
        if (!tokenResponse.indicatesSuccess()) {
            TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse;
            String error = errorResponse.getErrorObject().getCode();
            String errorDescription = errorResponse.getErrorObject().getDescription();
            if (errorDescription != null && !errorDescription.isEmpty()) {
                error += " : " + errorDescription;
            }
            log.error("error:" + error);
            log.trace("Leaving");
            throw new SocialUserAuthenticationException(error, SocialUserErrorIds.EXCEPTION);
        }
        AccessTokenResponse tokenSuccessResponse = (AccessTokenResponse) tokenResponse;
        // Get the access token, the server may also return a refresh token
        AccessToken accessToken = tokenSuccessResponse.getAccessToken();
        // try reading stuff from accesstoken
        Subject subject = new Subject();
        log.debug("claims from provider: " + accessToken.toJSONString());
        parsePrincipalsFromClaims(subject, accessToken.toJSONObject());
        if (getUserinfoEndpoint() != null && !getUserinfoEndpoint().toString().isEmpty()) {
            // The protected resource / web API
            URL resourceURL = new URL(getUserinfoEndpoint().toString());
            // Open the connection and include the token
            URLConnection conn = resourceURL.openConnection();
            conn.setRequestProperty("Authorization", accessToken.toAuthorizationHeader());
            String userinfo = IOUtils.toString(conn.getInputStream());
            conn.getInputStream().close();
            try {
                parsePrincipalsFromClaims(subject, JSONObjectUtils.parseJSONObject(userinfo));
            } catch (java.text.ParseException e) {
                log.error("error parsing userinfo endpoint");
                log.trace("Leaving");
                throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
            }
        }
        addDefaultPrincipals(subject);
        return subject;

    } catch (SerializeException | IOException | URISyntaxException | ParseException e) {
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
    }

}

From source file:org.ramadda.plugins.search.TwitterSearchProvider.java

/**
 * _more_//from w  w  w .j a  v a 2s . co m
 *
 * @param request _more_
 * @param searchCriteriaSB _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
@Override
public List<Entry> getEntries(Request request, Appendable searchCriteriaSB) throws Exception {

    List<Entry> entries = new ArrayList<Entry>();
    String url = URL;
    url = HtmlUtils.url(url, ARG_API_KEY, getApiKey(), ARG_Q, request.getString(ARG_TEXT, ""));
    System.err.println(getName() + " search url:" + url);
    URLConnection connection = new URL(url).openConnection();
    connection.setRequestProperty("User-Agent", "ramadda");
    InputStream is = connection.getInputStream();
    String json = IOUtil.readContents(is);
    //        System.out.println("xml:" + json);
    JSONObject obj = new JSONObject(new JSONTokener(json));
    if (!obj.has("items")) {
        System.err.println("YouTube SearchProvider: no items field in json:" + json);

        return entries;
    }

    JSONArray searchResults = obj.getJSONArray("items");
    Entry parent = getSynthTopLevelEntry();
    TypeHandler typeHandler = getRepository().getTypeHandler("media_youtubevideo");

    for (int i = 0; i < searchResults.length(); i++) {
        JSONObject item = searchResults.getJSONObject(i);
        JSONObject snippet = item.getJSONObject("snippet");
        String kind = Json.readValue(item, "id.kind", "");
        if (!kind.equals("youtube#video")) {
            System.err.println("? Youtube kind:" + kind);

            continue;
        }
        String id = Json.readValue(item, "id.videoId", "");
        String name = snippet.getString("title");
        String desc = snippet.getString("description");

        Date dttm = new Date();
        Date fromDate = DateUtil.parse(Json.readValue(snippet, "publishedAt", null));
        Date toDate = fromDate;

        String itemUrl = "https://www.youtube.com/watch?v=" + id;

        Entry newEntry = new Entry(Repository.ID_PREFIX_SYNTH + getId() + TypeHandler.ID_DELIMITER + id,
                typeHandler);
        entries.add(newEntry);

        String thumb = Json.readValue(snippet, "thumbnails.default.url", null);

        if (thumb != null) {
            Metadata thumbnailMetadata = new Metadata(getRepository().getGUID(), newEntry.getId(),
                    ContentMetadataHandler.TYPE_THUMBNAIL, false, thumb, null, null, null, null);
            newEntry.addMetadata(thumbnailMetadata);
        }

        newEntry.initEntry(name, desc, parent, getUserManager().getLocalFileUser(),
                new Resource(new URL(itemUrl)), "", dttm.getTime(), dttm.getTime(), fromDate.getTime(),
                toDate.getTime(), null);
        getEntryManager().cacheEntry(newEntry);
    }

    return entries;
}

From source file:org.silverpeas.calendar.ServletConnector.java

/**
 * Open a connection to the Silverpeas calendar importation servlet.
 *
 * @return a URLConnection object to connect to the Silverpeas calendar importation servlet.
 * @throws MalformedURLException/*from   w w w.  j a va2 s .  com*/
 * @throws IOException
 */
private final URLConnection getServletConnection() throws MalformedURLException, IOException {
    URL urlServlet = new URL(servletURL);
    URLConnection con = urlServlet.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type", "application/json");
    return con;
}

From source file:net.sourceforge.atunes.kernel.modules.proxy.Proxy.java

public URLConnection getConnection(URL u) throws IOException {
    URLConnection con = u.openConnection(this);
    String encodedUserPwd = new String(
            Base64.encodeBase64((StringUtils.getString(user, ':', password)).getBytes()));
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    return con;/* www  .  j  av  a2 s.c o m*/
}