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:com.synapticpath.pisecure.modules.LogglyEventLoggerModule.java

private void logEvent(SystemEvent event) {

    try {//from  ww  w .j a  v  a  2s  .c o m
        byte[] postData = event.toJson().getBytes(StandardCharsets.UTF_8);

        int postDataLength = postData.length;
        URL url = new URL(String.format(postRequestUrl, token, tag));

        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);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData);
        }

        if (conn.getResponseCode() == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.informatica.um.binge.api.impl.PluginsFactory.java

private InputStream getInputStream(String urlstr) throws VDSException {
    HttpURLConnection con = null;
    URL url;//from  w w  w . j  a  va2  s  . co  m
    try {
        url = new URL(urlstr);
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("GET");
        con.setUseCaches(false);
        con.connect();
        return con.getInputStream();
    } catch (MalformedURLException e) {
        throw new VDSException(VDSErrorCode.MALFORMED_ADMIND_URL, e, urlstr);
    } catch (IOException e) {
        throw new VDSException(VDSErrorCode.ADMIND_CONNECTION_ERROR, e, urlstr);
    }
}

From source file:api.wireless.gdata.client.TokenFactory.java

/**
 * Makes a HTTP POST request to the provided {@code url} given the
 * provided {@code parameters}.  It returns the output from the POST
 * handler as a String object.//from  w ww  .  j  av  a 2  s .  c o m
 *
 * @param url the URL to post the request
 * @param parameters the parameters to post to the handler
 * @return the output from the handler
 * @throws IOException if an I/O exception occurs while creating, writing,
 *                     or reading the request
 */
public String makePostRequest(URL url, Map<String, String> parameters) throws IOException {

    // Open connection      
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Form the POST parameters
    StringBuilder content = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        if (!first) {
            content.append("&");
        }
        content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("=");
        content.append(CharEscapers.uriEscaper().escape(parameter.getValue()));
        first = false;
    }

    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("utf-8"));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve the output
    InputStream inputStream = null;
    StringBuilder outputBuilder = new StringBuilder();
    try {
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }

        String string;
        if (inputStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (null != (string = reader.readLine())) {
                outputBuilder.append(string).append('\n');
            }
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return outputBuilder.toString();
}

From source file:org.bsc.maven.plugin.confluence.SwizzleApp.java

/**
 * //from  w w w. j  av a  2  s  .co m
 * @throws Exception 
 */
private void usingHttp() throws Exception {

    Confluence.ProxyInfo proxyInfo = null;

    Confluence confluence = confluence = ConfluenceFactory.createInstanceDetectingVersion(
            url.concat("/rpc/xmlrpc"), //args[0], 
            proxyInfo, username, //args[1], 
            password); //args[2]);

    Page page = confluence.getPage("CIRC", "Best Movies");

    java.io.InputStream is = null;
    java.io.FileOutputStream fos = null;
    try {
        final String req = String.format("%s/%s?pageId=%s", url, ExportFormat.PDF.url, page.getId());
        System.out.println(req);
        java.net.URL _url = new java.net.URL(req);

        HttpURLConnection urlConnection = (HttpURLConnection) _url.openConnection();
        //HttpURLConnection.setFollowRedirects(true);
        //urlConnection.setInstanceFollowRedirects(true);
        String userpass = username + ":" + password;

        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        urlConnection.addRequestProperty("Authorization", basicAuth);
        urlConnection.addRequestProperty("X-Atlassian-Token", "no-check");
        urlConnection.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

        urlConnection.setUseCaches(false);

        is = urlConnection.getInputStream();

        fos = new java.io.FileOutputStream("target/out.pdf");

        IOUtils.copy(is, fos);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.workfront.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }//ww  w  . j av  a  2s.  c o  m

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);

    return conn;
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

/**
 * Executes the message and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a response object containing the UPNP parsed response
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *//*from   ww  w  . j a  v  a  2s .  c  o  m*/
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.rogue.simpleclient.SimpleClient.java

/**
 * Connects to and authenticates with the Mojang auth server
 *
 * @since 1.0.0//from ww w  .  ja v a 2s . co  m
 * @version 1.0.0
 *
 * @param username The username/email to use
 * @param password The password to use
 * @throws IOException Incorrect credentials or some other connection error
 */
private void connect(String username, String password) throws IOException {
    HttpURLConnection http = (HttpURLConnection) this.url.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json");
    http.setUseCaches(false);
    http.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
        wr.writeBytes(this.getPayload(username, password).toJSONString());
        wr.flush();
    }
    StringBuilder sb = new StringBuilder();
    try (InputStreamReader is = new InputStreamReader(http.getInputStream());
            BufferedReader br = new BufferedReader(is)) {
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    }
    this.response = (JSONObject) JSONValue.parse(sb.toString());
}

From source file:com.zjut.material_wecenter.Client.java

/**
 * doPost ??POST/*from  www.  j ava  2  s.  c  o m*/
 * @param URL URL
 * @param params ?
 * @return ?NULL
 */
private String doPost(String URL, Map<String, String> params) {
    // 
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // ?
    try {
        URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // ??
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // ?
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // ?Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // ??
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            return new String(byteArrayOutputStream.toByteArray());
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}

From source file:org.cru.godtools.api.notifications.Sender.java

/**
 * Makes an HTTP POST request to a given endpoint.
 * <p/>//www.  j  a v a2 s  . 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 || body == null) {
        throw new IllegalArgumentException("arguments cannot be null");
    }
    if (!url.startsWith("https://")) {
        log.warn("URL does not use https: " + url);
    }
    log.info("Sending POST to " + url);
    log.info("POST body: " + body);
    byte[] bytes = body.getBytes();
    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.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Prepares a connection to the server./*from  www .jav  a2 s .  c  om*/
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    con.setConnectTimeout(connectionTimeoutMillis);
    con.setReadTimeout(readTimeoutMillis);
    con.setAllowUserInteraction(false);
    con.setDefaultUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");

    // do stuff for ssl
    if (HttpsURLConnection.class.isInstance(con)) {
        HttpsURLConnection https = HttpsURLConnection.class.cast(con);
        if (hostNameVerifier != null) {
            https.setHostnameVerifier(hostNameVerifier);
        }
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    // add headers
    con.setRequestProperty("Content-Type", "application/json-rpc");
    for (Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : extraHeaders.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // return it
    return con;
}