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:org.overlord.rtgov.tests.platforms.jbossas.slamonitor.JBossASSLAMonitorTest.java

public static java.util.List<?> performACMQuery(QuerySpec qs) throws Exception {
    URL getUrl = new URL("http://localhost:8080/overlord-rtgov/acm/query");
    HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
    connection.setRequestMethod("POST");

    connection.setDoOutput(true);/*  w  w  w  .  ja  v a  2  s  .c  o m*/
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/json");

    initAuth(connection);

    java.io.OutputStream os = connection.getOutputStream();

    MAPPER.writeValue(os, qs);

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

    java.io.InputStream is = connection.getInputStream();
    java.util.List<?> result = null;

    try {
        result = MAPPER.readValue(is, java.util.List.class);
    } catch (Exception e) {
        System.err.println("Exception when reading ACMQuery '" + qs + "': " + e);
        result = new java.util.ArrayList<Object>();
    }

    is.close();

    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./*ww  w . j  a  va2 s  . com*/
 *
 * 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:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.//from   w  w  w.j  av a  2  s. c  om
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:oauth.signpost.basic.DefaultOAuthProvider.java

protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Length", "0");
    return new HttpURLConnectionRequestAdapter(connection);
}

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetOtherFile(String uri) {
    TransportFetch result;/*from   w w w  . j a va2  s.co m*/
    try {
        final URL url = new URL(serverURL + uri);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetTheFile() {
    TransportFetch result;/*from  w  ww  . j  a  v a2  s . c o  m*/
    try {
        final URL url = new URL(serverURL + theFileURI);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static HttpURLConnection createConnection(String url, String username, String password)
        throws IOException {
    boolean useAuth = !password.equals("");
    // force SSL if useAuth=true (would send password unencrypted otherwise)
    boolean useSSL = useAuth || url.startsWith("https");

    Log.d("HttpPost", "password: " + password);
    Log.d("HttpPost", "useSSL: " + useSSL);

    if (useSSL) {
        if (!url.startsWith("https")) {
            // replace http: with https: -- this will obviously screw
            // up if input is something other than http so don't do that :)
            url = "https:" + url.substring(5);
        }/*from  w  ww.j av a  2s. c  o m*/

        // would rather not do this, need to check if there's still a problem
        // with our ssl certificates on NASA servers.
        try {
            DisableSSLCertificateCheckUtil.disableChecks();
        } catch (GeneralSecurityException e) {
            throw new IOException("HttpPost - disable ssl: " + e);
        }
    }

    HttpURLConnection conn;
    try {
        if (useSSL) {
            conn = (HttpsURLConnection) (new URL(url)).openConnection();
        } else {
            conn = (HttpURLConnection) (new URL(url)).openConnection();
        }
    } catch (IOException e) {
        throw new IOException("HttpPost - IOException: " + e);
    }

    if (useAuth) {
        // add pre-emptive http basic authentication.  using
        // homebrew version -- early versions of android
        // authenticator have problems and this is easy.
        String userpassword = username + ":" + password;
        String encodedAuthorization = Base64.encode(userpassword.getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
    }

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(true);

    return conn;
}

From source file:org.apache.jk.status.JkStatusAccessor.java

/**
 * Create a auth http connection for this url
 * /*from  ww  w .  j  a  va 2s  .  c om*/
 * @param url
 * @param username
 * @param password
 * @return HttpConnection
 * @throws IOException
 * @throws MalformedURLException
 * @throws ProtocolException
 */
protected HttpURLConnection openConnection(String url, String username, String password)
        throws IOException, MalformedURLException, ProtocolException {
    URLConnection conn;
    conn = (new URL(url)).openConnection();
    HttpURLConnection hconn = (HttpURLConnection) conn;

    // Set up standard connection characteristics
    hconn.setAllowUserInteraction(false);
    hconn.setDoInput(true);
    hconn.setUseCaches(false);
    hconn.setDoOutput(false);
    hconn.setRequestMethod("GET");
    hconn.setRequestProperty("User-Agent", "JkStatus-Client/1.0");

    if (username != null && password != null) {
        setAuthHeader(hconn, username, password);
    }
    // Establish the connection with the server
    hconn.connect();
    return hconn;
}

From source file:org.ringside.client.BaseRequestHandler.java

public URLConnection connectToServer(ApiMethod method, Parameters params, Context context) throws Exception {
    // are we ensured that our protocol is always one of either http or https
    // build our HTTP (or HTTPS) connection? this method assumes so
    CharSequence postString = params.implode('&');
    HttpURLConnection conn = (HttpURLConnection) context.getServerAddress().openConnection();
    conn.setAllowUserInteraction(false);
    conn.setConnectTimeout(60000);/*from   w  w w  .ja  va2s. co  m*/
    conn.setReadTimeout(60000);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Content-length", Integer.toString(postString.length()));
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod("POST");

    // connect to the server and write the parameters to the output
    conn.connect();
    conn.getOutputStream().write(postString.toString().getBytes());
    return conn;
}

From source file:org.ednovo.goorusearchwidget.WebService.java

public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;/*from   w  w w.java2  s.com*/
    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();
        Log.i("Response code :", "" + response);
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception e) {
        throw new IOException("Error connecting");
    } // end try-catch
    return in;
}