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

The following examples show how to use java.net.HttpURLConnection#setAllowUserInteraction() . 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
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(40000);
                httpURLConnection.setReadTimeout(timeout);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setAllowUserInteraction(false);
                httpURLConnection.setRequestMethod("POST");

                // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url);

                return httpURLConnection;
        }
 
Example 2
Source Project: jdk8u_jdk   File: B6401598.java    License: GNU General Public License v2.0 6 votes vote down vote up
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(40000);
                httpURLConnection.setReadTimeout(timeout);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setAllowUserInteraction(false);
                httpURLConnection.setRequestMethod("POST");

                // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url);

                return httpURLConnection;
        }
 
Example 3
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(40000);
                httpURLConnection.setReadTimeout(timeout);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setAllowUserInteraction(false);
                httpURLConnection.setRequestMethod("POST");

                // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url);

                return httpURLConnection;
        }
 
Example 4
Source Project: hadoop   File: JobEndNotifier.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Notify the URL just once. Use best effort.
 */
protected boolean notifyURLOnce() {
  boolean success = false;
  try {
    Log.info("Job end notification trying " + urlToNotify);
    HttpURLConnection conn =
      (HttpURLConnection) urlToNotify.openConnection(proxyToUse);
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setAllowUserInteraction(false);
    if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
      Log.warn("Job end notification to " + urlToNotify +" failed with code: "
      + conn.getResponseCode() + " and message \"" + conn.getResponseMessage()
      +"\"");
    }
    else {
      success = true;
      Log.info("Job end notification to " + urlToNotify + " succeeded");
    }
  } catch(IOException ioe) {
    Log.warn("Job end notification to " + urlToNotify + " failed", ioe);
  }
  return success;
}
 
Example 5
protected boolean isRunning() {
  try {
    URLConnection conn = new URL(this.baseUrl).openConnection();
    HttpURLConnection hconn = (HttpURLConnection) conn;
    hconn.setAllowUserInteraction(false);
    hconn.setDoInput(true);
    hconn.setUseCaches(false);
    hconn.setDoOutput(false);
    hconn.setRequestMethod("OPTIONS");
    hconn.setRequestProperty("User-Agent", "Camunda-Managed-SpringBoot-Container/1.0");
    hconn.setRequestProperty("Accept", "text/plain");
    hconn.connect();
    processResponse(hconn);
  } catch (Exception e) {
    return false;
  }
  return true;
}
 
Example 6
/** quick http client that allows no-dependency try at getting instance data. */
private static InputStream openStream(URI uri) throws IOException {
  HttpURLConnection connection = HttpURLConnection.class.cast(uri.toURL().openConnection());
  connection.setConnectTimeout(1000 * 2);
  connection.setReadTimeout(1000 * 2);
  connection.setAllowUserInteraction(false);
  connection.setInstanceFollowRedirects(false);
  return connection.getInputStream();
}
 
Example 7
/**
 * Start a new connection to a remote URL.
 *
 * @param url the remote URL
 * @return an open connection
 */
protected HttpURLConnection connectToURL(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setConnectTimeout(10000);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.setReadTimeout(60000);
    urlConnection.setUseCaches(true);
    urlConnection.connect();
    return urlConnection;
}
 
Example 8
Source Project: SPDS   File: URLConnTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test2() throws IOException {
    HttpURLConnection httpURLConnection = new HttpURLConnection(null) {

        @Override
        public void connect() throws IOException {
            // TODO Auto-generated method stub
            System.out.println("");
        }

        @Override
        public boolean usingProxy() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void disconnect() {
            // TODO Auto-generated method stub

        }
    };
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setAllowUserInteraction(false);

    httpURLConnection.connect();
    mustBeInAcceptingState(httpURLConnection);
}
 
Example 9
private static HttpURLConnection getURLConnection(String requestUrl) throws IOException {
    URL url = new URL(requestUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setReadTimeout(30000);
    conn.setConnectTimeout(15000);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    return conn;
}
 
Example 10
Source Project: Android-Example   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream OpenHttpConnection(String urlString) 
throws IOException
{
    InputStream in = null;
    int response = -1;
            
    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection();
              
    if (!(conn instanceof HttpURLConnection))                     
        throw new IOException("Not an HTTP connection");
     
    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect(); 
 
        response = httpConn.getResponseCode();                 
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }                     
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");            
    }
    return in;     
}
 
Example 11
protected void placeOrder() throws IOException {
    URL url = new URL("http://localhost:8180/orders/createOrder");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("GET");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type",
            "application/json");

    connection.connect();

    java.io.InputStream is = connection.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    StringBuilder builder = new StringBuilder();
    String str = null;

    while ((str = reader.readLine()) != null) {
        builder.append(str);
    }

    is.close();

    assertEquals("Unexpected response code", 200, connection.getResponseCode());

    assertEquals(ORDER_CREATED, builder.toString());
}
 
Example 12
/**
 * Start a new connection to a remote URL.
 *
 * @param url the remote URL
 * @return an open connection
 */
protected HttpURLConnection connectToURL(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setConnectTimeout(10000);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.setReadTimeout(60000);
    urlConnection.setUseCaches(true);
    urlConnection.connect();
    return urlConnection;
}
 
Example 13
Source Project: dropbox-sdk-java   File: StandardHttpRequestor.java    License: MIT License 5 votes vote down vote up
private HttpURLConnection prepRequest(String url, Iterable<Header> headers, boolean streaming) throws IOException {
    URL urlObject = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection(config.getProxy());

    conn.setConnectTimeout((int) config.getConnectTimeoutMillis());
    conn.setReadTimeout((int) config.getReadTimeoutMillis());
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    if (streaming) {
        conn.setChunkedStreamingMode(IOUtil.DEFAULT_COPY_BUFFER_SIZE);
    }

    // Some JREs (like the one provided by Google AppEngine) will return HttpURLConnection
    // instead of HttpsURLConnection. So we have to check here.
    if (conn instanceof HttpsURLConnection) {
        SSLConfig.apply((HttpsURLConnection) conn);
        configureConnection((HttpsURLConnection) conn);
    } else {
        logCertificatePinningWarning();
    }

    configure(conn);

    for (Header header : headers) {
        conn.addRequestProperty(header.getKey(), header.getValue());
    }

    return conn;
}
 
Example 14
public static HttpURLConnection createConnection(URL url, long lastModifiedMillis, SslConfiguration sslConfiguration)
    throws IOException {
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    AuthorizationProvider provider = ConfigurationFactory.getAuthorizationProvider();
    if (provider != null) {
        provider.addAuthorization(urlConnection);
    }
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setRequestMethod("GET");
    if (connectTimeoutMillis > 0) {
        urlConnection.setConnectTimeout(connectTimeoutMillis);
    }
    if (readTimeoutMillis > 0) {
        urlConnection.setReadTimeout(readTimeoutMillis);
    }
    String[] fileParts = url.getFile().split("\\.");
    String type = fileParts[fileParts.length - 1].trim();
    String contentType = isXml(type) ? XML : isJson(type) ? JSON : isProperties(type) ? PROPERTIES : TEXT;
    urlConnection.setRequestProperty("Content-Type", contentType);
    if (lastModifiedMillis > 0) {
        urlConnection.setIfModifiedSince(lastModifiedMillis);
    }
    if (url.getProtocol().equals(HTTPS) && sslConfiguration != null) {
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
        if (!sslConfiguration.isVerifyHostName()) {
            ((HttpsURLConnection) urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
        }
    }
    return urlConnection;
}
 
Example 15
protected void sendRequestUsingInputStream(URL url, String method, boolean fault) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);

    connection.addRequestProperty("test-header", "test-value");
    if (fault) {
        connection.addRequestProperty("test-fault", "true");
    }

    try (InputStream is = connection.getInputStream()) {
    } catch (IOException ioe) {
        if (!fault) {
            throw ioe;
        }
    }

    int status = connection.getResponseCode();

    if (!fault) {
        assertEquals("Unexpected response code", 200, status);
    } else {
        assertEquals("Unexpected fault response code", 401, status);
    }

    // Call again to make sure does not attempt to finish the span again
    connection.getResponseCode();

    verifyTrace(url, method, fault);
}
 
Example 16
@Test
public void testGetWithBadURL() {
    String path = null;

    try {
        URL url = new URL(BAD_URL);
        path = url.getPath();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Content-Type",
                "application/json");

        connection.connect();

        fail("ConnectException was not thrown");
    } catch (ConnectException ce) {

    } catch (Exception e) {
        fail("Failed to perform get: " + e);
    }

    Wait.until(() -> getApmMockServer().getTraces().size() == 1);

    // Check stored traces (including 1 for the test client)
    assertEquals(1, getApmMockServer().getTraces().size());

    List<Producer> producers = NodeUtil.findNodes(getApmMockServer().getTraces().get(0).getNodes(), Producer.class);

    assertEquals("Expecting 1 producers", 1, producers.size());

    Producer testProducer = producers.get(0);

    assertEquals(path, testProducer.getUri());
    assertEquals("Connection refused", producers.get(0).getProperties(Constants.PROP_FAULT).iterator().next().getValue());
}
 
Example 17
Source Project: neoscada   File: Processor.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private boolean shouldUpload ( final MavenReference ref ) throws Exception
{
    System.out.format ( "baseline validation: %s%n", ref );

    final String group = ref.getGroupId ().replace ( '.', '/' );

    final String uri = String.format ( "http://central.maven.org/maven2/%s/%s/%s/%s", group, ref.getArtifactId (), ref.getVersion (), ref.toFileName () );

    final URL url = new URL ( uri );
    final HttpURLConnection con = openConnection ( url );
    con.setAllowUserInteraction ( false );

    con.setConnectTimeout ( getInteger ( "maven.central.connectTimeout", getInteger ( "maven.central.timeout", 0 ) ) );
    con.setReadTimeout ( getInteger ( "maven.central.readTimeout", getInteger ( "maven.central.timeout", 0 ) ) );

    con.connect ();
    try
    {
        final int rc = con.getResponseCode ();
        System.out.format ( "\t%s -> %s%n", url, rc );
        if ( rc == 404 )
        {
            // file is not there ... upload
            return true;
        }

        final Path tmp = Files.createTempFile ( null, ".jar" );
        try
        {
            try ( final InputStream in = con.getInputStream ();
                  final OutputStream out = Files.newOutputStream ( tmp ) )
            {
                ByteStreams.copy ( in, out );
            }

            performBaselineCheck ( makeJarFile ( makeVersionBase ( ref ), ref ), tmp );
        }
        finally
        {
            Files.deleteIfExists ( tmp );
        }
    }
    finally
    {
        con.disconnect ();
    }

    // don't upload, since the bundle is already there
    return false;
}
 
Example 18
private static String fetchImageViaHttp(URL imgUrl) throws IOException {
    String sURL = imgUrl.toString();
    String imgFile = imgUrl.getPath();
    HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
    String uri = null;
    try {
        conn.setAllowUserInteraction(false);
        conn.setDoOutput(true);
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("User-Agent", user_agent);
        conn.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1));
        conn.connect();
         
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
             
        InputStream imgData = conn.getInputStream();
        String ext = FilenameUtils.getExtension(imgFile).toLowerCase();
        
        if (!isImageFile("aa." + ext)) {
            ext = "jpg";
        }
        
        uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext;
        
        System.err.println(uri);
 
        File fileDest = new File(img_path + uri);
        if (!fileDest.getParentFile().exists()) {
            fileDest.getParentFile().mkdirs();
        }
         
        FileOutputStream fos = new FileOutputStream(fileDest);
        
        try {
            IOUtils.copy(imgData, fos);
        } finally {
            IOUtils.closeQuietly(imgData);
            IOUtils.closeQuietly(fos);
        }
        
    } finally {
        conn.disconnect();
    }
    return img_path + uri;
}
 
Example 19
Source Project: feign   File: Client.java    License: Apache License 2.0 4 votes vote down vote up
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
  final URL url = new URL(request.url());
  final HttpURLConnection connection = this.getConnection(url);
  if (connection instanceof HttpsURLConnection) {
    HttpsURLConnection sslCon = (HttpsURLConnection) connection;
    if (sslContextFactory != null) {
      sslCon.setSSLSocketFactory(sslContextFactory);
    }
    if (hostnameVerifier != null) {
      sslCon.setHostnameVerifier(hostnameVerifier);
    }
  }
  connection.setConnectTimeout(options.connectTimeoutMillis());
  connection.setReadTimeout(options.readTimeoutMillis());
  connection.setAllowUserInteraction(false);
  connection.setInstanceFollowRedirects(options.isFollowRedirects());
  connection.setRequestMethod(request.httpMethod().name());

  Collection<String> contentEncodingValues = request.headers().get(CONTENT_ENCODING);
  boolean gzipEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_GZIP);
  boolean deflateEncodedRequest =
      contentEncodingValues != null && contentEncodingValues.contains(ENCODING_DEFLATE);

  boolean hasAcceptHeader = false;
  Integer contentLength = null;
  for (String field : request.headers().keySet()) {
    if (field.equalsIgnoreCase("Accept")) {
      hasAcceptHeader = true;
    }
    for (String value : request.headers().get(field)) {
      if (field.equals(CONTENT_LENGTH)) {
        if (!gzipEncodedRequest && !deflateEncodedRequest) {
          contentLength = Integer.valueOf(value);
          connection.addRequestProperty(field, value);
        }
      } else {
        connection.addRequestProperty(field, value);
      }
    }
  }
  // Some servers choke on the default accept string.
  if (!hasAcceptHeader) {
    connection.addRequestProperty("Accept", "*/*");
  }

  if (request.body() != null) {
    if (disableRequestBuffering) {
      if (contentLength != null) {
        connection.setFixedLengthStreamingMode(contentLength);
      } else {
        connection.setChunkedStreamingMode(8196);
      }
    }
    connection.setDoOutput(true);
    OutputStream out = connection.getOutputStream();
    if (gzipEncodedRequest) {
      out = new GZIPOutputStream(out);
    } else if (deflateEncodedRequest) {
      out = new DeflaterOutputStream(out);
    }
    try {
      out.write(request.body());
    } finally {
      try {
        out.close();
      } catch (IOException suppressed) { // NOPMD
      }
    }
  }
  return connection;
}
 
Example 20
@Override
public void send(final Layout<?> layout, final LogEvent event) throws IOException {
    final HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setRequestMethod(method);
    if (connectTimeoutMillis > 0) {
        urlConnection.setConnectTimeout(connectTimeoutMillis);
    }
    if (readTimeoutMillis > 0) {
        urlConnection.setReadTimeout(readTimeoutMillis);
    }
    if (layout.getContentType() != null) {
        urlConnection.setRequestProperty("Content-Type", layout.getContentType());
    }
    for (final Property header : headers) {
        urlConnection.setRequestProperty(
            header.getName(),
            header.isValueNeedsLookup() ? getConfiguration().getStrSubstitutor().replace(event, header.getValue()) : header.getValue());
    }
    if (sslConfiguration != null) {
        ((HttpsURLConnection)urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
    }
    if (isHttps && !verifyHostname) {
        ((HttpsURLConnection)urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
    }

    final byte[] msg = layout.toByteArray(event);
    urlConnection.setFixedLengthStreamingMode(msg.length);
    urlConnection.connect();
    try (OutputStream os = urlConnection.getOutputStream()) {
        os.write(msg);
    }

    final byte[] buffer = new byte[1024];
    try (InputStream is = urlConnection.getInputStream()) {
        while (IOUtils.EOF != is.read(buffer)) {
            // empty
        }
    } catch (final IOException e) {
        final StringBuilder errorMessage = new StringBuilder();
        try (InputStream es = urlConnection.getErrorStream()) {
            errorMessage.append(urlConnection.getResponseCode());
            if (urlConnection.getResponseMessage() != null) {
                errorMessage.append(' ').append(urlConnection.getResponseMessage());
            }
            if (es != null) {
                errorMessage.append(" - ");
                int n;
                while (IOUtils.EOF != (n = es.read(buffer))) {
                    errorMessage.append(new String(buffer, 0, n, CHARSET));
                }
            }
        }
        if (urlConnection.getResponseCode() > -1) {
            throw new IOException(errorMessage.toString());
        } else {
            throw e;
        }
    }
}