Example usage for java.net HttpURLConnection setDefaultUseCaches

List of usage examples for java.net HttpURLConnection setDefaultUseCaches

Introduction

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

Prototype

public void setDefaultUseCaches(boolean defaultusecaches) 

Source Link

Document

Sets the default value of the useCaches field to the specified value.

Usage

From source file:org.openbravo.test.datasource.DatasourceTestUtil.java

static HttpURLConnection createConnection(String url, String wsPart, String method, String cookie)
        throws Exception {

    String completeUrl = url + wsPart;
    log.debug("Create conntection URL: {}, method {}", completeUrl, method);
    final URL connUrl = new URL(completeUrl);
    final HttpURLConnection hc = (HttpURLConnection) connUrl.openConnection();
    hc.setRequestMethod(method);//from w  w  w . ja  v a2s .  c om
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    if (cookie != null) {
        hc.setRequestProperty("Cookie", cookie);
    }
    return hc;
}

From source file:com.gmt2001.HttpRequest.java

public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) {
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    HttpResponse r = new HttpResponse();

    r.type = type;/*  w  w  w  .  jav a2  s  .  co m*/
    r.url = url;
    r.post = post;
    r.headers = headers;

    try {
        URL u = new URL(url);

        HttpURLConnection h = (HttpURLConnection) u.openConnection();

        for (Entry<String, String> e : headers.entrySet()) {
            h.addRequestProperty(e.getKey(), e.getValue());
        }

        h.setRequestMethod(type.name());
        h.setUseCaches(false);
        h.setDefaultUseCaches(false);
        h.setConnectTimeout(timeout);
        h.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        if (!post.isEmpty()) {
            h.setDoOutput(true);
        }

        h.connect();

        if (!post.isEmpty()) {
            BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream());
            stream.write(post.getBytes());
            stream.flush();
            stream.close();
        }

        if (h.getResponseCode() < 400) {
            r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding());
            r.httpCode = h.getResponseCode();
            r.success = true;
        } else {
            r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding());
            r.httpCode = h.getResponseCode();
            r.success = false;
        }
    } catch (IOException ex) {
        r.success = false;
        r.httpCode = 0;
        r.exception = ex.getMessage();

        com.gmt2001.Console.err.printStackTrace(ex);
    }

    return r;
}

From source file:ostepu.request.httpRequest.java

/**
 * fhrt eine benutzerdefinierte Anfrage aus (falls eine besondere
 * Anfrageform bentigt wird)//from  w w  w  .  j  a  v a2s .co  m
 *
 * @param url     die Zieladresse
 * @param method  die Aufrufmethode (sowas wie GET, POST, DELETE)
 * @param content der Anfrageinhalt
 * @param auth    eine Authentifizierungsmethode (noAuth, httpAuth)
 * @return das Anfrageresultat
 */
public static httpRequestResult custom(String url, String method, String content, authentication auth) {
    URL urlurl;
    try {
        urlurl = new URL(url);
    } catch (MalformedURLException ex) {
        Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
        return new httpRequestResult(500, new byte[] {});
    }
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) urlurl.openConnection();
    } catch (IOException ex) {
        Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
        return new httpRequestResult(500, new byte[] {});
    }

    try {
        connection.setRequestMethod(method);
    } catch (ProtocolException ex) {
        // falsche Methode
        Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
        return new httpRequestResult(500, new byte[] {});
    }
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    // connection.setIfModifiedSince(0);
    // connection.setRequestProperty("Cache-Control","no-cache");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    if (auth != null) {
        auth.performAuth(connection);
    }

    if (!"".equals(content)) {
        connection.setRequestProperty("Content-Length", String.valueOf(content.length()));
    }

    // fhrt die Anfrage aus
    OutputStreamWriter writer = null;
    httpRequestResult Result;
    try {
        if (!"".equals(content)) {
            try {
                writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(content);
                writer.flush();
            } catch (IOException ex) {
                Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
                return new httpRequestResult(500, new byte[] {});
            }
        }
    } finally {
        Result = new httpRequestResult();
        try {
            Result.setStatus(connection.getResponseCode());
        } catch (IOException ex) {
            Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
            return new httpRequestResult(500, new byte[] {});
        }

        Result.setHeaders(connection.getHeaderFields());
        // Result.setContent((String) connection.getContent());
        InputStream stream = connection.getErrorStream();
        if (stream == null) {
            try {
                stream = connection.getInputStream();
            } catch (IOException e) {
                stream = null;
            }
        }

        if (stream != null) {
            // This is a try with resources, Java 7+ only
            // If you use Java 6 or less, use a finally block instead
            byte[] res;
            try {
                res = IOUtils.toByteArray(stream);
                stream.close();
            } catch (IOException ex) {
                Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
                return new httpRequestResult(500, new byte[] {});
            }
            Result.setContent(res);
        } else {
            Result.setContent("".getBytes());
        }

        Result.setMethod(method);
        Result.setUrl(url);
    }

    // ab hier wird die Antwort zusammengebaut
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException ex) {
            // der Stream konnte nicht geschlossen werden
            Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex);
            return new httpRequestResult(500, new byte[] {});
        }
    }
    connection.disconnect();

    return Result;
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Utility to get the bytes at a protected uri
 *
 * This will retrieve the URL if a username and password are provided.
 * The java.net.URL class does not do Basic Authentication, so we have to
 * do it manually in this routine.//from   w  ww. j ava 2 s .c  o m
 *
 * If no username is provided, we create an InputSource from the uri
 * and let the InputSource go fetch the contents.
 *
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 */
private static InputSource getInputSourceFromURI(String uri, String username, String password)
        throws IOException, ProtocolException, UnsupportedEncodingException {
    URL wsdlurl = null;
    try {
        wsdlurl = new URL(uri);
    } catch (MalformedURLException e) {
        // we can't process it, it might be a 'simple' foo.wsdl
        // let InputSource deal with it
        return new InputSource(uri);
    }

    // if no authentication, just let InputSource deal with it
    if (username == null && wsdlurl.getUserInfo() == null) {
        return new InputSource(uri);
    }

    // if this is not an HTTP{S} url, let InputSource deal with it
    if (!wsdlurl.getProtocol().startsWith("http")) {
        return new InputSource(uri);
    }

    URLConnection connection = wsdlurl.openConnection();
    // Does this work for https???
    if (!(connection instanceof HttpURLConnection)) {
        // can't do http with this URL, let InputSource deal with it
        return new InputSource(uri);
    }
    HttpURLConnection uconn = (HttpURLConnection) connection;
    String userinfo = wsdlurl.getUserInfo();
    uconn.setRequestMethod("GET");
    uconn.setAllowUserInteraction(false);
    uconn.setDefaultUseCaches(false);
    uconn.setDoInput(true);
    uconn.setDoOutput(false);
    uconn.setInstanceFollowRedirects(true);
    uconn.setUseCaches(false);

    // username/password info in the URL overrides passed in values
    String auth = null;
    if (userinfo != null) {
        auth = userinfo;
    } else if (username != null) {
        auth = (password == null) ? username : username + ":" + password;
    }

    if (auth != null) {
        uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding)));
    }

    uconn.connect();

    return new InputSource(uconn.getInputStream());
}

From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java

private HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override//w  w w .  j av  a2s .c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:petascope.wcps.server.test.XmlTestOnline.java

/**
 * Send an XML request to the WCPS server. Hopefully it will succeed.
 * Returns a message on error or null otherwise.
 **//*from  ww w  .j  a  va2s.c  om*/
public String runOneTest(String param, String xml) throws MalformedURLException, IOException {

    //        System.out.println("--------------------");
    //        System.out.println(xml);
    //        System.out.println("\t--------------------");

    // connect to the servlet
    URL servlet = new URL(PetascopeURL);
    HttpURLConnection conn = (HttpURLConnection) servlet.openConnection();

    // inform the connection that we will send output and accept input
    conn.setDoInput(true);
    conn.setDoOutput(true);

    // Don't use a cached version of URL connection.
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);

    // Send POST request
    conn.setRequestMethod("POST");

    // Specify the content type that we will send binary data
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    String service = "service=WCPS&";
    String data = service + param + "=" + xml;
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line1 = cgiOutput.readLine();
    String line2 = cgiOutput.readLine();
    String line3 = cgiOutput.readLine();
    System.out.println("\t" + line1);
    System.out.println("\t" + line2);
    System.out.println("\t" + line3);

    if (line1 != null && line2 != null && line3 != null && line2.equals("<h1>An error has occured</h1>")) {
        System.out.println("Error executing query: ");
        String error = line3.substring(10, line3.length() - 4);
        System.out.println("\t" + error);
        return error;
    } else {
        return null;
    }

}

From source file:petascope.wcps.server.test.GrammarTestOnline.java

/**
 * Send an XML request to the WCPS server. Hopefully it will succeed.
 * Returns a message on error or null otherwise.
 **//*from  w w w  . jav a2  s . co m*/
public String runOneTest(String param, String query) throws MalformedURLException, IOException {

    //        System.out.println("--------------------");
    //        System.out.println(query);
    //        System.out.println("\t--------------------");

    // connect to the servlet
    URL servlet = new URL(PetascopeURL);
    HttpURLConnection conn = (HttpURLConnection) servlet.openConnection();

    // inform the connection that we will send output and accept input
    conn.setDoInput(true);
    conn.setDoOutput(true);

    // Don't use a cached version of URL connection.
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);

    // Send POST request
    conn.setRequestMethod("POST");

    // Specify the content type that we will send binary data
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    String data = param + "=" + StringUtil.urlencode(query);
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line1 = cgiOutput.readLine();
    String line2 = cgiOutput.readLine();
    String line3 = cgiOutput.readLine();
    System.out.println("\t" + line1);
    System.out.println("\t" + line2);
    System.out.println("\t" + line3);

    if (line1 != null && line2 != null && line3 != null && line2.equals("<h1>An error has occured</h1>")) {
        while (cgiOutput.ready()) {
            System.out.println("\t" + cgiOutput.readLine());
        }
        //            System.out.println("Error executing query: ");
        String error = line3.substring(10, line3.length() - 4);
        //            System.out.println("\t" + error);
        return error;
    } else {
        return null;
    }

}

From source file:fr.insalyon.creatis.vip.datamanager.applet.upload.UploadFilesBusiness.java

@Override
public void run() {
    try {//www  .j a  v a2  s .  c  om

        SwingUtilities.invokeAndWait(beforeRunnable);

        File fileToUpload = null;
        boolean single = true;

        if (dataList.size() == 1 && new File(dataList.get(0)).isFile()) {
            fileToUpload = new File(dataList.get(0));

        } else {

            String fileName = System.getProperty("java.io.tmpdir") + "/file-" + System.nanoTime() + ".zip";
            FolderZipper.zipListOfData(dataList, fileName);
            fileToUpload = new File(fileName);
            zipFileName = fileToUpload.getName();
            single = false;
        }

        // Call Servlet
        URL servletURL = new URL(codebase + "/fr.insalyon.creatis.vip.portal.Main/uploadfilesservice");
        HttpURLConnection servletConnection = (HttpURLConnection) servletURL.openConnection();
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        servletConnection.setChunkedStreamingMode(4096);

        servletConnection.setRequestProperty("vip-cookie-session", sessionId);
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
        servletConnection.setRequestProperty("Content-Length", Long.toString(fileToUpload.length()));

        servletConnection.setRequestProperty("path", path);
        servletConnection.setRequestProperty("fileName", fileToUpload.getName());
        servletConnection.setRequestProperty("single", single + "");
        servletConnection.setRequestProperty("unzip", unzip + "");
        servletConnection.setRequestProperty("pool", usePool + "");

        long fileSize = fileToUpload.length();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileToUpload));
        OutputStream os = servletConnection.getOutputStream();

        try {
            byte[] buffer = new byte[4096];
            long done = 0;
            while (true) {
                int bytes = bis.read(buffer);
                if (bytes < 0) {
                    break;
                }
                done += bytes;
                os.write(buffer, 0, bytes);
                progressRunnable.setValue((int) (done * 100 / fileSize));
                SwingUtilities.invokeAndWait(progressRunnable);
            }
            os.flush();

        } finally {
            os.close();
            bis.close();
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(servletConnection.getInputStream()));
        String operationID = null;
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("id=")) {
                    operationID = line.split("=")[1];
                }
                System.out.println(line);
            }
        } finally {
            reader.close();
        }

        if (!single) {
            fileToUpload.delete();
        }

        if (deleteDataList) {
            for (String data : dataList) {
                FileUtils.deleteQuietly(new File(data));
            }
        }

        result = operationID;
        SwingUtilities.invokeAndWait(afterRunnable);

    } catch (Exception ex) {
        result = ex.getMessage();
        SwingUtilities.invokeLater(errorRunnable);
    }
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Creates a HTTP connection.//w ww. ja  va 2 s  .  c o  m
 * 
 * @param wsPart
 * @param method
 *          POST, PUT, GET or DELETE
 * @return the created connection
 * @throws Exception
 */
protected HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    log.debug(method + ": " + getOpenbravoURL() + wsPart);
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:us.nineworlds.plex.rest.PlexappFactory.java

/**
 * @param resourceURL//from   w w w .  ja va 2  s  .c  o  m
 * @param con
 * @return
 */
protected boolean requestSuccessful(String resourceURL) {
    HttpURLConnection con = null;
    try {
        URL url = new URL(resourceURL);
        con = (HttpURLConnection) url.openConnection();
        con.setDefaultUseCaches(false);
        int responseCode = con.getResponseCode();
        if (responseCode == 200) {
            return true;
        }
    } catch (Exception ex) {
        return false;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
    return false;
}