Example usage for java.net HttpURLConnection setUseCaches

List of usage examples for java.net HttpURLConnection setUseCaches

Introduction

In this page you can find the example usage for java.net HttpURLConnection setUseCaches.

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    // System.out.println(text.length()+ " "+text.substring(0,
    // Math.min(text.length(), 15)));
    // TODO: workaround for a bug in tagme. should be deleted afterwards.
    String newText = "";
    for (int i = 0; i < text.length(); i++)
        newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i));
    text = newText;//w w w  .j a  va 2s .c o  m

    // avoid crashes for empty documents
    int j = 0;
    while (j < text.length() && text.charAt(j) == ' ')
        j++;
    if (j == text.length())
        return new HashSet<ScoredAnnotation>();

    HashSet<ScoredAnnotation> res;
    String params = null;
    try {
        res = new HashSet<ScoredAnnotation>();

        params = "key=" + this.key;
        params += "&lang=en";
        if (epsilon >= 0)
            params += "&epsilon=" + epsilon;
        if (minComm >= 0)
            params += "&min_comm=" + minComm;
        if (minLink >= 0)
            params += "&min_link=" + minLink;
        params += "&text=" + URLEncoder.encode(text, "UTF-8");
        URL wikiApi = new URL(url);

        HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
        slConnection.setRequestProperty("accept", "text/xml");
        slConnection.setDoOutput(true);
        slConnection.setDoInput(true);
        slConnection.setRequestMethod("POST");
        slConnection.setRequestProperty("charset", "utf-8");
        slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
        slConnection.setUseCaches(false);
        slConnection.setReadTimeout(0);

        DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        Scanner s = new Scanner(slConnection.getInputStream());
        Scanner s2 = s.useDelimiter("\\A");
        String resultStr = s2.hasNext() ? s2.next() : "";
        s.close();

        JSONObject obj = (JSONObject) JSONValue.parse(resultStr);
        lastTime = (Long) obj.get("time");

        JSONArray jsAnnotations = (JSONArray) obj.get("annotations");
        for (Object js_ann_obj : jsAnnotations) {
            JSONObject js_ann = (JSONObject) js_ann_obj;
            System.out.println(js_ann);
            int start = ((Long) js_ann.get("start")).intValue();
            int end = ((Long) js_ann.get("end")).intValue();
            int id = ((Long) js_ann.get("id")).intValue();
            float rho = Float.parseFloat((String) js_ann.get("rho"));
            System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")");
            res.add(new ScoredAnnotation(start, end - start, id, (float) rho));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage()
                + " Parameters:" + params);
    }
    return res;

}

From source file:com.juick.android.Utils.java

public static RESTResponse postJSON(final Context context, final String url, final String data,
        final String contentType) {
    final URLAuth authorizer = getAuthorizer(url);
    final RESTResponse[] ret = new RESTResponse[] { null };
    final boolean[] cookieCleared = new boolean[] { false };
    authorizer.authorize(context, false, false, url, new Function<Void, String>() {
        @Override/*from w ww .  j a  v  a  2  s  .  co m*/
        public Void apply(String myCookie) {
            final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH);
            if (noAuthRequested)
                myCookie = null;
            HttpURLConnection conn = null;
            try {
                String nurl = authorizer.authorizeURL(url, myCookie);
                URL jsonURL = new URL(nurl);
                conn = (HttpURLConnection) jsonURL.openConnection();
                if (contentType != null) {
                    conn.addRequestProperty("Content-Type", contentType);
                }
                authorizer.authorizeRequest(context, conn, myCookie, nurl);

                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.close();

                URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false);
                try {
                    if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) {
                        ret[0] = new RESTResponse(NO_AUTH, false, null);
                    } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) {
                        cookieCleared[0] = true; // don't enter loop
                        final Function<Void, String> thiz = this;
                        authorizer.clearCookie(context, new Runnable() {
                            @Override
                            public void run() {
                                authorizer.authorize(context, true, false, url, thiz);
                            }
                        });
                    } else {
                        if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) {
                            InputStream inputStream = conn.getInputStream();
                            ret[0] = streamToString(inputStream, null);
                            inputStream.close();
                        } else {
                            ret[0] = new RESTResponse(
                                    "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false,
                                    null);
                        }
                    }
                } finally {
                    conn.disconnect();
                }
            } catch (Exception e) {
                Log.e("getJSON", e.toString());
                ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return null; //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    while (ret[0] == null) { // bad, but true
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return ret[0];
}

From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java

@Override
public void run() {
    debug("THREAD STARTED");
    long start = getNow();
    while (start + TIMEOUT <= getNow() && player == null) {
    }/*www . ja  v a2 s . c o  m*/
    this.stopThread();
    this.deregister();
    if (player == null)
        return;

    boolean alreadyActivated = false;
    boolean isActivated = false;

    try {
        String x = player.getSavedVariable("xenforo");
        alreadyActivated = x.equalsIgnoreCase("yes");
    } catch (Exception e) {
    }

    try {
        String url = XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "") + APPEND;
        if (url.equals(APPEND))
            return;

        String encodedData = "name=" + encode("username") + "&value=" + encode(this.player.getPlayer())
                + "&_xfResponseType=json";
        //String rawData = "name=username";
        String type = "application/x-www-form-urlencoded; charset=UTF-8";
        //String encodedData = URLEncoder.encode(rawData, "ISO-8859-1"); 
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", type);
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Referer", XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", ""));
        conn.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(encodedData);
        wr.flush();

        InputStream in = conn.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        String out = responseStrBuilder.toString();
        JSONObject o = (JSONObject) JSONValue.parse(out);
        try {
            isActivated = o.get("_redirectMessage").toString().equalsIgnoreCase("ok");
        } catch (NullPointerException e) {
            isActivated = true;
        }
        debug("GOT: " + isActivated);
    } catch (Exception e) {
        if (DebugMode)
            e.printStackTrace();
        return;
    }

    player.setSavedVariable("xenforo", (isActivated ? "yes" : "no"));
    player.save();

    if (isActivated && !alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onRegistered"));
    }

    if (!isActivated && alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onDeRegistered"));
    }
}

From source file:org.elasticsearch.metrics.ElasticsearchReporter.java

/**
 * Open a new HttpUrlConnection, in case it fails it tries for the next host in the configured list
 *//*from  w  ww  . j ava  2  s  .c  o  m*/
private HttpURLConnection openConnection(String uri, String method) {
    for (String host : hosts) {
        try {
            URL templateUrl = new URL("http://" + host + uri);
            HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection();
            connection.setRequestMethod(method);
            connection.setConnectTimeout(timeout);
            connection.setUseCaches(false);
            if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
                connection.setDoOutput(true);
            }
            connection.connect();

            return connection;
        } catch (IOException e) {
            LOGGER.error("Error connecting to {}: {}", host, e);
        }
    }

    return null;
}

From source file:com.dawg6.d3api.server.D3IO.java

private <T> T readValue(ObjectMapper mapper, URL url, Class<T> clazz, int retries)
        throws JsonParseException, JsonMappingException, IOException {

    //      log.info("URL " + url);

    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);/*w  w  w  .  j  av  a 2  s  .  c  o m*/
    c.setConnectTimeout(connectTimeout);
    c.setReadTimeout(readTimeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
    case 200:
    case 201:
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        try {
            mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            return mapper.readValue(sb.toString(), clazz);
        } catch (Exception e) {
            log.severe("JSON = " + sb.toString());
            log.log(Level.SEVERE, e.getMessage());

            return null;
        }

    case 408:
    case 504:
        log.info("HTTP Response: " + status + ", retries = " + retries + ", URL: " + url);
        errors++;
        onError(status);

        if (retries > 0) {
            retryAttempts++;
            onRetry();
            return readValue(mapper, url, clazz, retries - 1);
        } else
            return null;

    default:
        log.severe("HTTP Response: " + status + ", URL: " + url);
        return null;
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public String uploadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    InputStream in = null;//from   ww  w .ja v  a2  s . co  m
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        URL url = new URL(pURL);
        System.out.println("Uploading file: " + pLocalFile.getName() + " to " + url.getHost());
        performHeadHTTPMethod(url);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";"
                + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1");
        byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1");

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //conn.setRequestProperty("Content-Length",len + "");
        long len = header.length + pLocalFile.length() + footer.length;
        conn.setFixedLengthStreamingMode((int) len);
        out = new BufferedOutputStream(conn.getOutputStream(), BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[CHUNK_SIZE];
        int length;
        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(pLocalFile.length(), new DigestInputStream(
                new BufferedInputStream(new FileInputStream(pLocalFile), BUFFER_CAPACITY), md));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.write(footer);
        out.flush();

        manageHTTPCode(conn);

        byte[] digest = md.digest();
        return Base64.encodeBase64String(digest);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:be.appfoundry.custom.google.android.gcm.server.Sender.java

/**
 * Makes an HTTP POST request to a given endpoint.
 * <p/>/*w w  w  .  j a v a 2s  . c  o m*/
 * <p/>
 * <strong>Note: </strong> the returned connected should not be disconnected,
 * otherwise it would kill persistent connections made using Keep-Alive.
 *
 * @param url         endpoint to post the request.
 * @param contentType type of request.
 * @param body        body of the request.
 * @return the underlying connection.
 * @throws IOException propagated from underlying methods.
 */
protected HttpURLConnection post(String url, String contentType, String body) throws IOException {
    if (url == null || contentType == null || body == null) {
        throw new IllegalArgumentException("arguments cannot be null");
    }
    if (!url.startsWith("https://")) {
        logger.warning("URL does not use https: " + url);
    }
    logger.fine("Sending POST to " + url);
    logger.finest("POST body: " + body);
    byte[] bytes = body.getBytes(UTF8);
    HttpURLConnection conn = getConnection(url);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", contentType);
    conn.setRequestProperty("Authorization", "key=" + key);
    OutputStream out = conn.getOutputStream();
    try {
        out.write(bytes);
    } finally {
        close(out);
    }
    return conn;
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * Open a new HttpUrlConnection, in case it fails it tries for the next host in the configured list
 *  We use search fqdn , if the exception is there we will retry ). Now just using a fixed sleep
 *  //TODO add a more generic support for hosts array*
 */// ww  w .j a  va2  s .  com
private HttpURLConnection openConnection(String uri, String method) {
    for (int j = 0; j < ES_CONNECT_RETRIES; ++j)
        try {
            URL templateUrl = new URL("http://" + hosts[0] + uri);
            HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection();
            connection.setRequestMethod(method);
            connection.setConnectTimeout(timeout);
            connection.setUseCaches(false);
            if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
                connection.setDoOutput(true);
            }
            connection.connect();

            return connection;
        } catch (IOException e) {
            try {

                TimeUnit.MILLISECONDS.sleep(SLEEP_BEFORE_RETRY_IN_MILLIS);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
            LOGGER.error(
                    "Error connecting to {}: {}; " + (j + 1) + " Attempt failed  of  " + ES_CONNECT_RETRIES,
                    hosts[0], e);
        }
    return null;
}

From source file:com.portfolio.data.attachment.XSLService.java

HttpURLConnection CreateConnection(String url, HttpServletRequest request)
        throws MalformedURLException, IOException {
    /// Create connection
    URL urlConn = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) urlConn.openConnection();
    connection.setDoOutput(true);/*www .  j  av  a  2s  .c  o  m*/
    connection.setUseCaches(false); /// We don't want to cache data
    connection.setInstanceFollowRedirects(false); /// Let client follow any redirection
    String method = request.getMethod();
    connection.setRequestMethod(method);

    String context = request.getContextPath();
    connection.setRequestProperty("app", context);

    /// Transfer headers
    String key = "";
    String value = "";
    Enumeration<String> header = request.getHeaderNames();
    while (header.hasMoreElements()) {
        key = header.nextElement();
        value = request.getHeader(key);
        connection.setRequestProperty(key, value);
    }

    return connection;
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Sends request to Equifax./*from  w  w w .  jav a2  s .c o m*/
 * @param server {@link String}
 * @param send {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
public String sendToEquifax(final String server, final String send) throws IOException {

    String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit";

    byte[] postData = params.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;

    URL url = new URL(server);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);

    Reader in = null;
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);

        StringBuilder sb = new StringBuilder();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c = in.read(); c != -1; c = in.read()) {
            sb.append((char) c);
        }

        String receive = sb.toString();

        return receive;

    } finally {

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

        if (wr != null) {
            wr.close();
        }
    }
}