Java Code Examples for java.net.HttpURLConnection#setDefaultUseCaches()

The following examples show how to use java.net.HttpURLConnection#setDefaultUseCaches() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: datacollector   File: Configs.java    License: Apache License 2.0 6 votes vote down vote up
void validateConnectivity(Stage.Context context, List<Stage.ConfigIssue> issues) {
  boolean ok = false;
  List<String> errors = new ArrayList<>();
  for (String hostPort : hostPorts) {
    try {
      HttpURLConnection conn = createConnection(hostPort);
      conn.setRequestMethod("GET");
      conn.setDefaultUseCaches(false);
      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        if (Constants.X_SDC_PING_VALUE.equals(conn.getHeaderField(Constants.X_SDC_PING_HEADER))) {
          ok = true;
        } else {
          issues.add(context.createConfigIssue(Groups.RPC.name(), HOST_PORTS,
                                               Errors.IPC_DEST_12, hostPort ));
        }
      } else {
        errors.add(Utils.format("'{}': {}", hostPort, conn.getResponseMessage()));
      }
    } catch (Exception ex) {
      errors.add(Utils.format("'{}': {}", hostPort, ex.toString()));
    }
  }
  if (!ok) {
    issues.add(context.createConfigIssue(null, null, Errors.IPC_DEST_15, errors));
  }
}
 
Example 2
private static void downloadToFile(String url, File f) throws IOException {
    URL u = new URL(url);
    URLConnection conn = u.openConnection();
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection http = (HttpURLConnection)conn;
        http.setInstanceFollowRedirects(true);
        http.setDefaultUseCaches(false);
        
    }
    
    try (InputStream input = conn.getInputStream()) {
        try (FileOutputStream output = new FileOutputStream(f)) {
            byte[] buf = new byte[128 * 1024];
            int len;
            while ((len = input.read(buf)) >= 0) {
                output.write(buf, 0, len);
            }
        }
    }
}
 
Example 3
Source Project: jsonrpc4j   File: JsonRpcHttpClient.java    License: MIT License 6 votes vote down vote up
/**
 * Prepares a connection to the server.
 *
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
	
	// create URLConnection
	HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
	connection.setConnectTimeout(connectionTimeoutMillis);
	connection.setReadTimeout(readTimeoutMillis);
	connection.setAllowUserInteraction(false);
	connection.setDefaultUseCaches(false);
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setUseCaches(false);
	connection.setInstanceFollowRedirects(true);
	connection.setRequestMethod("POST");
	
	setupSsl(connection);
	addHeaders(extraHeaders, connection);
	
	return connection;
}
 
Example 4
private void test(List<RestApi> apis, boolean authzEnabled) throws Exception {
  String baseUrl = startServer(authzEnabled);
  try {
    for (RestApi api : apis) {
      Set<String> has = api.roles;
      for (String user : ALL_ROLES) {
        user = "guest";
        URL url = new URL(baseUrl + api.uriPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
        if (authzEnabled) {
          conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64URLSafeString((user + ":" + user).getBytes()));
        }
        conn.setRequestMethod(api.method.name());
        conn.setDefaultUseCaches(false);
        if (authzEnabled) {
          if (has.contains(user)) {
            Assert.assertNotEquals(
                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user, api.method, api.uriPath),
                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
          } else {
            Assert.assertEquals(
                Utils
                    .format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user, api.method, api.uriPath),
                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
          }
        } else {
          Assert.assertNotEquals(
              Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user, api.method, api.uriPath),
              HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
        }
      }
    }
  } finally {
    stopServer();
  }
}
 
Example 5
Source Project: datacollector   File: SdcIpcTarget.java    License: Apache License 2.0 5 votes vote down vote up
HttpURLConnection createWriteConnection(boolean isRetry) throws IOException, StageException {
  HttpURLConnection  conn = config.createConnection(getHostPort(isRetry));
  conn.setRequestMethod("POST");
  conn.setRequestProperty(Constants.CONTENT_TYPE_HEADER, Constants.APPLICATION_BINARY);
  conn.setRequestProperty(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER, "true");
  conn.setDefaultUseCaches(false);
  conn.setDoOutput(true);
  conn.setDoInput(true);
  return conn;
}
 
Example 6
Source Project: Ninja   File: ReadabilityTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(Void... params) {
    try {
        URL url = new URL(query);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDefaultUseCaches(true);
        connection.setUseCaches(true);
        connection.connect();

        if (connection.getResponseCode() == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            connection.disconnect();

            result = new JSONObject(builder.toString());
        } else {
            result = null;
        }
    } catch (Exception e) {
        result = null;
    }

    if (isCancelled()) {
        return false;
    }
    return true;
}
 
Example 7
public static boolean doesETagMatch(DownloadResponse resp, URL url, String etag, boolean followRedirects) throws IOException {
    if (etag == null) {
        return false;
    }
    //log("Checking etag for "+url);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    if (resp != null) {
        resp.setConnection(conn);
    }
    if (Boolean.getBoolean("client4j.disableHttpCache")) {
        conn.setUseCaches(false);
        conn.setDefaultUseCaches(false);
    }
    conn.setRequestMethod("HEAD");
    //https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download
    conn.setInstanceFollowRedirects(followRedirects);
    
    int response = conn.getResponseCode();
    logger.fine(""+conn.getHeaderFields());
    String newETag = conn.getHeaderField("ETag");
    //log("New etag is "+newETag+", old="+etag);
    
    if (newETag != null) {
        return etag.equals(ETags.sanitize(newETag));
    } else {
        return false;
    }
}
 
Example 8
@Test
public void testPostPetStatus() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/webapp/pets/petstore/pets";

    URL url = new URL(endpointAddress);
    HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();

    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setDefaultUseCaches(false);
    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setDoInput(true);
    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Accept",   "text/xml");
    httpUrlConnection.setRequestProperty("Content-type",   "application/x-www-form-urlencoded");
    httpUrlConnection.setRequestProperty("Connection",   "close");

    OutputStream outputstream = httpUrlConnection.getOutputStream();

    File inputFile = new File(getClass().getResource("resources/singleValPostBody.txt").toURI());

    byte[] tmp = new byte[4096];
    int i = 0;
    try (InputStream is = new FileInputStream(inputFile)) {
        while ((i = is.read(tmp)) >= 0) {
            outputstream.write(tmp, 0, i);
        }
    }

    outputstream.flush();

    int responseCode = httpUrlConnection.getResponseCode();
    assertEquals(200, responseCode);
    assertEquals("Wrong status returned", "open", getStringFromInputStream(httpUrlConnection
        .getInputStream()));
    httpUrlConnection.disconnect();
}
 
Example 9
@Test
public void testAddBookHTTPURL() throws Exception {
    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/books";

    URL url = new URL(endpointAddress);
    HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();

    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setDefaultUseCaches(false);
    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setDoInput(true);
    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Accept",   "text/xml");
    httpUrlConnection.setRequestProperty("Content-type",   "application/xml");
    httpUrlConnection.setRequestProperty("Connection",   "close");
    //httpurlconnection.setRequestProperty("Content-Length",   String.valueOf(is.available()));

    OutputStream outputstream = httpUrlConnection.getOutputStream();
    File inputFile = new File(getClass().getResource("resources/add_book.txt").toURI());

    byte[] tmp = new byte[4096];
    int i = 0;
    try (InputStream is = new FileInputStream(inputFile)) {
        while ((i = is.read(tmp)) >= 0) {
            outputstream.write(tmp, 0, i);
        }
    }

    outputstream.flush();

    int responseCode = httpUrlConnection.getResponseCode();
    assertEquals(200, responseCode);

    InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
    assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                 stripXmlInstructionIfNeeded(getStringFromInputStream(httpUrlConnection
                                                                      .getInputStream())));
    httpUrlConnection.disconnect();
}
 
Example 10
/**
 * NGW API Functions
 */

public static String getConnectionCookie(
        AtomicReference<String> reference,
        String login,
        String password)
        throws IOException
{
    String sUrl = reference.get();
    if (!sUrl.startsWith("http")) {
        sUrl = "http://" + sUrl;
        reference.set(sUrl);
    }

    sUrl += "/login";
    String sPayload = "login=" + login + "&password=" + password;
    final HttpURLConnection conn = NetworkUtil.getHttpConnection("POST", sUrl, null, null);
    if (null == conn) {
        Log.d(TAG, "Error get connection object: " + sUrl);
        return null;
    }
    conn.setInstanceFollowRedirects(false);
    conn.setDefaultUseCaches(false);
    conn.setDoOutput(true);
    conn.connect();

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(sPayload);

    writer.flush();
    writer.close();
    os.close();

    int responseCode = conn.getResponseCode();
    if (!(responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM)) {
        Log.d(TAG, "Problem execute post: " + sUrl + " HTTP response: " + responseCode);
        return null;
    }

    String headerName;
    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equals("Set-Cookie")) {
            return conn.getHeaderField(i);
        }
    }

    if (!sUrl.startsWith("https")) {
        sUrl = sUrl.replace("http", "https").replace("/login", "");
        reference.set(sUrl);
    }

    return getConnectionCookie(reference, login, password);
}