Example usage for java.net HttpURLConnection setAllowUserInteraction

List of usage examples for java.net HttpURLConnection setAllowUserInteraction

Introduction

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

Prototype

public void setAllowUserInteraction(boolean allowuserinteraction) 

Source Link

Document

Set the value of the allowUserInteraction field of this URLConnection .

Usage

From source file:com.attask.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);
    }//from   w w  w  . j  a  va 2s .co  m

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

    return conn;
}

From source file:dk.clarin.tools.workflow.java

/**
* Sends an HTTP GET request to a url/*from   w  ww .  j  a  va2 s.  c om*/
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestString - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/

public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat,
        String filename, String jobID, boolean postmethod) {
    int code = 0;
    String message = "";
    //String filelist;
    if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
        // Send a GET or POST request to the servlet
        try {
            // Construct data
            String requestResult = "";
            String urlStr = endpoint;
            if (postmethod) // HTTP POST
            {
                logger.debug("HTTP POST");
                StringReader input = new StringReader(requestString);
                StringWriter output = new StringWriter();
                URL endp = new URL(endpoint);

                HttpURLConnection urlc = null;
                try {
                    urlc = (HttpURLConnection) endp.openConnection();
                    try {
                        urlc.setRequestMethod("POST");
                    } catch (ProtocolException e) {
                        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
                    }
                    urlc.setDoOutput(true);
                    urlc.setDoInput(true);
                    urlc.setUseCaches(false);
                    urlc.setAllowUserInteraction(false);
                    urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

                    OutputStream out = urlc.getOutputStream();

                    try {
                        Writer writer = new OutputStreamWriter(out, "UTF-8");
                        pipe(input, writer);
                        writer.close();
                    } catch (IOException e) {
                        throw new Exception("IOException while posting data", e);
                    } finally {
                        if (out != null)
                            out.close();
                    }
                } catch (IOException e) {
                    throw new Exception("Connection error (is server running at " + endp + " ?): " + e);
                } finally {
                    if (urlc != null) {
                        code = urlc.getResponseCode();

                        if (code == 200) {
                            got200(result, BracMat, filename, jobID, urlc.getInputStream());
                        } else {
                            InputStream in = urlc.getInputStream();
                            try {
                                Reader reader = new InputStreamReader(in);
                                pipe(reader, output);
                                reader.close();
                                requestResult = output.toString();
                            } catch (IOException e) {
                                throw new Exception("IOException while reading response", e);
                            } finally {
                                if (in != null)
                                    in.close();
                            }
                            logger.debug("urlc.getResponseCode() == {}", code);
                            message = urlc.getResponseMessage();
                            didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                    postmethod, urlStr, message, requestResult);
                        }
                        urlc.disconnect();
                    } else {
                        code = 0;
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                }
                //requestResult = output.toString();
                logger.debug("postData returns " + requestResult);
            } else // HTTP GET
            {
                logger.debug("HTTP GET");
                // Send data

                if (requestString != null && requestString.length() > 0) {
                    urlStr += "?" + requestString;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                conn.connect();

                // Cast to a HttpURLConnection
                if (conn instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) conn;
                    code = httpConnection.getResponseCode();
                    logger.debug("httpConnection.getResponseCode() == {}", code);
                    message = httpConnection.getResponseMessage();
                    BufferedReader rd;
                    StringBuilder sb = new StringBuilder();
                    ;
                    //String line;
                    if (code == 200) {
                        got200(result, BracMat, filename, jobID, httpConnection.getInputStream());
                    } else {
                        // Get the error response
                        rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
                        int nextChar;
                        while ((nextChar = rd.read()) != -1) {
                            sb.append((char) nextChar);
                        }
                        rd.close();
                        requestResult = sb.toString();
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                } else {
                    code = 0;
                    didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod,
                            urlStr, message, requestResult);
                }
            }
            logger.debug("Job " + jobID + " receives status code [" + code + "] from tool.");
        } catch (Exception e) {
            //jobs = 0; // No more jobs to process now, probably the tool is not reachable
            logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage());
            /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
        }
    } else {
        //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all
        logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint
                + ")");
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
    return code;
}

From source file:org.codehaus.httpcache4j.urlconnection.URLConnectionResponseResolver.java

private void configureConnection(HttpURLConnection connection) {
    if (configuration.getConnectTimeout() > 0) {
        connection.setConnectTimeout(configuration.getConnectTimeout());
    }//from w w  w.  ja v  a2  s. c  o  m
    if (configuration.getReadTimeout() > 0) {
        connection.setReadTimeout(configuration.getReadTimeout());
    }
    connection.setAllowUserInteraction(false);
}

From source file:org.hawkular.apm.client.api.rest.AbstractRESTClient.java

public HttpURLConnection getConnectionForRequest(String tenantId, URL url, String method) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(method);
    connection.setDoOutput(true);//from  www  .ja v  a2  s  . co  m
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    addHeaders(connection, tenantId);
    return connection;
}

From source file:de.uni.stuttgart.informatik.ToureNPlaner.Net.Handler.SyncCoreLoader.java

private long getLastModifiedOnServer() throws IOException {
    HttpURLConnection con = null;
    long result = new Date().getTime();
    try {/* w  w w .java 2 s .  co m*/
        URL url = new URL(coreURL + pathPrefix + corePrefix + coreLevel + coreSuffix);
        con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("HEAD");
        con.setDoInput(true);
        con.setAllowUserInteraction(false);
        result = con.getHeaderFieldDate("Last-Modified", result);
        Log.d(TAG, "Last modified is parsed " + new Date(result));

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return result;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
    return result;
}

From source file:org.jumpmind.symmetric.transport.http.HttpTransportManager.java

protected int sendMessage(URL url, String data) throws IOException {
    HttpURLConnection conn = openConnection(url, getBasicAuthUsername(), getBasicAuthPassword());
    conn.setRequestMethod("POST");
    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);/*  ww w .j a  va  2 s. com*/
    conn.setConnectTimeout(getHttpTimeOutInMs());
    conn.setReadTimeout(getHttpTimeOutInMs());
    OutputStream os = conn.getOutputStream();
    try {
        writeMessage(os, data);
        return conn.getResponseCode();
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;/* ww  w  .j  av a 2s . co  m*/
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

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

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

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

/**
 * Creates a HTTP connection.//from ww  w  .  j  a  v  a  2s.c om
 * 
 * @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:de.ingrid.iplug.csw.dsc.cswclient.impl.XMLPostRequest.java

/**
 * Send the given request to the server.
 * @param serverURL/* ww w.  jav a  2 s .co  m*/
 * @param payload
 * @return Document
 * @throws Exception 
 */
protected Document sendRequest(String requestURL, OMElement payload) throws Exception {
    // and make the call
    Document result = null;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(requestURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setAllowUserInteraction(false);
        conn.setReadTimeout(10000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "text/xml");
        conn.connect();

        // send the request
        String xmlToSend = serializeElement(payload.cloneOMElement());
        if (log.isDebugEnabled())
            log.debug("Request: " + xmlToSend);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(xmlToSend);
        wr.flush();
        wr.close();

        // Get response data.
        int code = conn.getResponseCode();
        if (code >= 200 && code < 300) {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            result = builder.parse(conn.getInputStream());
        }
        conn.disconnect();
        conn = null;
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return result;
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

/**
 * Connection helper//from w  ww.j av a2  s . co m
 * @param url
 * @param method
 * @param setDoOutput
 * @return
 * @throws IOException
 */
private HttpURLConnection createConnection(URL url, String method, boolean setDoOutput) throws IOException {
    HttpURLConnection conn = null;
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setAllowUserInteraction(false);
    conn.setRequestMethod(method);
    conn.setDoOutput(setDoOutput);

    if (session_cookie != null) {
        conn.setRequestProperty("Cookie", session_cookie);
    }

    return conn;
}