Example #1
3
  private static HttpURLConnection createConnection(URL url, Map<String, String> header)
      throws ProtocolException {
    HttpURLConnection httpURLConnection = null;

    try {
      httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException var4) {
      var4.printStackTrace();
      return null;
    }

    httpURLConnection.setConnectTimeout(CONNECTION_TIME_OUT);
    httpURLConnection.setReadTimeout(READ_TIME_OUT);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setUseCaches(false);
    Iterator<String> headerIterator = header.keySet().iterator();
    while (headerIterator.hasNext()) {
      String key = headerIterator.next();
      httpURLConnection.setRequestProperty(key, header.get(key));
    }
    httpURLConnection.setRequestMethod("POST");
    if ("https".equalsIgnoreCase(url.getProtocol())) {
      HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
      husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
      husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());
      return husn;
    } else {
      return httpURLConnection;
    }
  }
Example #2
0
    public void run() {
      URLConnection con = null;
      try {
        con = url.openConnection();

        if ("HTTPS".equalsIgnoreCase(url.getProtocol())) {
          HttpsURLConnection scon = (HttpsURLConnection) con;
          try {
            scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias, trustAnyCert));
            HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel);
            if (hv != null) {
              scon.setHostnameVerifier(hv);
            }
          } catch (GeneralSecurityException e) {
            Debug.logError(e, module);
          } catch (GenericConfigException e) {
            Debug.logError(e, module);
          }
        }
      } catch (IOException e) {
        Debug.logError(e, module);
      }

      synchronized (URLConnector.this) {
        if (timedOut && con != null) {
          close(con);
        } else {
          connection = con;
          URLConnector.this.notify();
        }
      }
    }
Example #3
0
  /**
   * Contacts the remote URL and returns the response.
   *
   * @param constructedUrl the url to contact.
   * @param hostnameVerifier Host name verifier to use for HTTPS connections.
   * @param encoding the encoding to use.
   * @return the response.
   */
  public static String getResponseFromServer(
      final URL constructedUrl, final HostnameVerifier hostnameVerifier, final String encoding) {
    URLConnection conn = null;
    try {
      conn = constructedUrl.openConnection();
      if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
      }
      final BufferedReader in;

      if (CommonUtils.isEmpty(encoding)) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      } else {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
      }

      String line;
      final StringBuilder stringBuffer = new StringBuilder(255);

      while ((line = in.readLine()) != null) {
        stringBuffer.append(line);
        stringBuffer.append("\n");
      }
      return stringBuffer.toString();
    } catch (final Exception e) {
      LOG.error(e.getMessage(), e);
      throw new RuntimeException(e);
    } finally {
      if (conn != null && conn instanceof HttpURLConnection) {
        ((HttpURLConnection) conn).disconnect();
      }
    }
  }
  @Override
  protected HttpURLConnection openConnection(String path, String query) throws IOException {
    query = addDelegationTokenParam(query);
    final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    // bypass hostname verification
    try {
      conn.setHostnameVerifier(new DummyHostnameVerifier());
      conn.setRequestMethod("GET");
      conn.connect();
    } catch (IOException ioe) {
      throwIOExceptionFromConnection(conn, ioe);
    }

    // check cert expiration date
    final int warnDays = ExpWarnDays;
    if (warnDays > 0) { // make sure only check once
      ExpWarnDays = 0;
      long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis();
      X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates();
      if (clientCerts != null) {
        for (X509Certificate cert : clientCerts) {
          long expTime = cert.getNotAfter().getTime();
          if (expTime < expTimeThreshold) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName());
            int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            LOG.warn(sb.toString());
          }
        }
      }
    }
    return (HttpURLConnection) conn;
  }
  private Boolean doInBackground2(String... params) {
    try {
      URL url = new URL(params[0]);
      URLConnection connection = url.openConnection();

      if ("https".equals(url.getProtocol())) {
        if (sslSocketFactory == null)
          Log.w(TAG, "HTTPS requested but no sslSocketFactory provided");
        else {
          HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;
          Log.i(TAG, "Configuring the SSL factory: " + sslSocketFactory);
          httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
          httpsUrlConnection.setHostnameVerifier(
              new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                  return true;
                }
              });
        }
      }
      Log.i(TAG, connection.toString());
      connection.connect();

      fileSize = connection.getContentLength();
      Log.i(TAG, "fileSize=" + fileSize);

      File targetFile = new File(params[1]);
      File parentDir = targetFile.getParentFile();

      if (!parentDir.exists()) {
        parentDir.mkdirs();
      }
      if (!parentDir.exists() || !parentDir.isDirectory()) {
        Log.e(TAG, "Could not create the directory: \"" + parentDir + "\"");
        return false;
      }

      InputStream input = new BufferedInputStream(url.openStream());
      OutputStream output = new FileOutputStream(targetFile);

      byte data[] = new byte[10 * 1024];
      long transferred = 0;
      long count;
      while ((count = input.read(data)) != -1) {
        transferred += count;
        publishProgress(transferred, fileSize);
        output.write(data, 0, (int) count);
      }

      output.flush();
      output.close();
      input.close();
    } catch (Exception e) {
      Log.e(TAG, "Got exception: ", e);
      return false;
    }
    return true;
  }
  public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
      throws AccessTokenException {
    SSLContext ctx;
    String response = "";
    try {
      ctx = SSLContext.getInstance("TLS");

      ctx.init(
          new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
      SSLContext.setDefault(ctx);

      URL url = new URL(tokenURL);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(
          new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
              return true;
            }
          });
      // System.out.println(conn.getResponseCode());
      conn.disconnect();

      HttpClient httpClient = new HttpClient();

      PostMethod postMethod = new PostMethod(tokenURL);
      postMethod.addParameter(new NameValuePair("grant_type", grantType));
      postMethod.addParameter(new NameValuePair("username", username));
      postMethod.addParameter(new NameValuePair("password", password));
      postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

      postMethod.addRequestHeader("Authorization", "Basic " + appToken);
      postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      httpClient.executeMethod(postMethod);

      response = postMethod.getResponseBodyAsString();
      log.info(response);
      JSONObject jsonObject = new JSONObject(response);

      AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
      accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
      accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
      accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
      accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

      return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {

      log.error(e.getMessage());
      throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

      return null;
    }
  }
 private void setHostnameVerifier(HttpsURLConnection conn) {
   conn.setHostnameVerifier(
       new HostnameVerifier() {
         @Override
         public boolean verify(String hostname, SSLSession session) {
           return true;
         }
       });
 }
Example #8
0
  private HttpURLConnection getConnection(final String url_string) throws IOException {

    final HttpURLConnection con;
    final Proxy proxy;
    if (isProxyConfigured()) {
      if (CONF.getHttpProxyUser() != null && !CONF.getHttpProxyUser().equals("")) {
        if (logger.isDebugEnabled()) {
          logger.debug("Proxy AuthUser: "******"Proxy AuthPassword: "******"Opening proxied connection("
                + CONF.getHttpProxyHost()
                + ":"
                + CONF.getHttpProxyPort()
                + ")");
      }
    } else {
      proxy = Proxy.NO_PROXY;
    }

    final URL url = new URL(url_string);
    con = (HttpURLConnection) url.openConnection(proxy);
    if (CONF.getHttpConnectionTimeout() > 0) {
      con.setConnectTimeout(CONF.getHttpConnectionTimeout());
    }
    if (CONF.getHttpReadTimeout() > 0) {
      con.setReadTimeout(CONF.getHttpReadTimeout());
    }
    con.setInstanceFollowRedirects(false);
    if (con instanceof HttpsURLConnection && CONF.isSSLErrorIgnored()) {
      ((HttpsURLConnection) con).setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);
      if (IGNORE_ERROR_SSL_FACTORY != null) {
        ((HttpsURLConnection) con).setSSLSocketFactory(IGNORE_ERROR_SSL_FACTORY);
      }
    }
    return con;
  }
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    try {
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {

      e.printStackTrace();
    }
    URL console = null;
    try {
      console = new URL(url);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection conn;
    try {
      conn = (HttpsURLConnection) console.openConnection();
      conn.setRequestMethod("POST");
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setRequestProperty("Accept", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json"
      String inpputs = contentdata;
      OutputStream os = conn.getOutputStream();
      os.write(inpputs.getBytes());
      os.close();
      conn.connect();
      InputStream is = conn.getInputStream();
      // // DataInputStream indata = new DataInputStream(is);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String ret = "";
      while (ret != null) {
        ret = reader.readLine();
        if (ret != null && !ret.trim().equals("")) {
          str_return = str_return + ret;
        }
      }
      is.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return str_return;
  }
Example #10
0
  /**
   * Call this with any HttpURLConnection, and it will modify the trust settings if it is an HTTPS
   * connection.
   */
  public static void relaxHostChecking(final HttpURLConnection conn)
      throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    if (conn instanceof HttpsURLConnection) {
      final HttpsURLConnection httpsConnection = (HttpsURLConnection) conn;
      final SSLSocketFactory factory = prepFactory(httpsConnection);
      httpsConnection.setSSLSocketFactory(factory);
      httpsConnection.setHostnameVerifier(TRUSTING_HOSTNAME_VERIFIER);
    }
  }
Example #11
0
 private void setupSsl(HttpURLConnection connection) {
   if (HttpsURLConnection.class.isInstance(connection)) {
     HttpsURLConnection https = HttpsURLConnection.class.cast(connection);
     if (hostNameVerifier != null) {
       https.setHostnameVerifier(hostNameVerifier);
     }
     if (sslContext != null) {
       https.setSSLSocketFactory(sslContext.getSocketFactory());
     }
   }
 }
Example #12
0
 /**
  * Open HTTPS connection. Use this method to setup and accept all SSL certificates from HTTPS
  * protocol.
  *
  * @param url
  * @return
  * @throws IOException
  */
 public static HttpsURLConnection openSConnection(String url) throws IOException {
   URL theURL = new URL(url);
   trustAllHosts();
   HttpsURLConnection https = (HttpsURLConnection) theURL.openConnection();
   https.setHostnameVerifier(
       new HostnameVerifier() {
         public boolean verify(String hostname, SSLSession session) {
           return true;
         }
       });
   return https;
 }
    private String downloadUrl(String urlString)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
            CertificateException {

      HostnameVerifier hostnameVerifier =
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
              return hv.verify("localhost", session);
            }
          };
      URL url = new URL(urlString);
      HttpsURLConnection conn = null;
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          activity.getApplicationContext().getResources().openRawResource(R.raw.mykeystore);
      try {
        // Initialize the keystore with the provided trusted
        // certificates
        // Also provide the password of the keystore
        trusted.load(in, "my_password".toCharArray());
      } finally {
        in.close();
      }
      String algorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
      tmf.init(trusted);

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(hostnameVerifier);
      conn.setSSLSocketFactory(context.getSocketFactory());
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.setRequestProperty("Accept", "text/xml");
      conn.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encodeToString(
                  ((this.userName + ":" + this.passWord).getBytes()), Base64.NO_WRAP));
      // Starts the query
      conn.connect();
      return conn.getResponseMessage();
    }
  public static String PostData(String strUrl, String strData) {
    StringBuilder strResult = new StringBuilder("");

    try {
      URL url = new URL(strUrl);
      HttpURLConnection urlConnection = null;

      if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();

        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        urlConnection = https;
      } else {
        urlConnection = (HttpURLConnection) url.openConnection();
      }

      urlConnection.setDefaultUseCaches(false);
      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true);
      urlConnection.setRequestMethod("POST");

      urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");

      OutputStreamWriter outStream =
          new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
      PrintWriter writer = new PrintWriter(outStream);
      writer.write(strData.toString());
      writer.flush();

      if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

        BufferedReader in =
            new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
          strResult.append(inputLine);
        }
      } else {
        strResult.append(urlConnection.getResponseCode());
      }
    } catch (MalformedURLException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    }

    return strResult.toString();
  }
 @VisibleForTesting
 protected HttpURLConnection openConnection(URL url) throws IOException {
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   if (sslShuffle) {
     HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
     try {
       httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
     } catch (GeneralSecurityException ex) {
       throw new IOException(ex);
     }
     httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
   }
   return conn;
 }
Example #16
0
  private static void configureAllowAll(HttpsURLConnection connection) {
    connection.setHostnameVerifier(
        new HostnameVerifier() {
          @Override
          public boolean verify(String s, SSLSession sslSession) {
            return true;
          }
        });

    try {
      connection.setSSLSocketFactory(getSocketFactory());
    } catch (Exception e) {
      throw new RuntimeException("XTrust Failed to set SSL Socket factory", e);
    }
  }
  public static void trustAllCertsForConnection(HttpURLConnection httpURLConnection) {
    if (httpURLConnection instanceof HttpsURLConnection) {
      HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;

      setTrustAllCerts(httpsURLConnection);

      httpsURLConnection.setHostnameVerifier(
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          });
    }
  }
 @Override
 protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
   URLConnection connection = super.openConnection(url, proxy);
   if (connection instanceof HttpsURLConnection) {
     HttpsURLConnection urlConnection = (HttpsURLConnection) connection;
     HostnameVerifier hostnameVerifier = urlConnection.getHostnameVerifier();
     if (hostnameVerifier != kindHostnameVerifier) {
       urlConnection.setHostnameVerifier(kindHostnameVerifier);
     }
     if (trustedSslSocketFactory != null) {
       urlConnection.setSSLSocketFactory(trustedSslSocketFactory);
     }
   }
   return connection;
 }
Example #19
0
  private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal) throws IOException {

    if ((httpPrincipal == null) || (httpPrincipal.getUrl() == null)) {
      return null;
    }

    URL url = new URL(httpPrincipal.getUrl() + "/api/liferay/do");

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

    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);

    if (!_VERIFY_SSL_HOSTNAME && (httpURLConnection instanceof HttpsURLConnection)) {

      HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;

      httpsURLConnection.setHostnameVerifier(
          new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          });
    }

    httpURLConnection.setRequestProperty(
        HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_JAVA_SERIALIZED_OBJECT);
    httpURLConnection.setUseCaches(false);

    httpURLConnection.setRequestMethod("POST");

    if (Validator.isNotNull(httpPrincipal.getLogin())
        && Validator.isNotNull(httpPrincipal.getPassword())) {

      String userNameAndPassword =
          httpPrincipal.getLogin() + StringPool.COLON + httpPrincipal.getPassword();

      httpURLConnection.setRequestProperty(
          HttpHeaders.AUTHORIZATION,
          HttpServletRequest.BASIC_AUTH
              + StringPool.SPACE
              + Base64.encode(userNameAndPassword.getBytes()));
    }

    return httpURLConnection;
  }
Example #20
0
  private void request(
      String method, String url, KVPair[] args, KVPair[] body, String urlEncode, int timeout)
      throws Exception {

    if (urlEncode == null || urlEncode.trim().isEmpty()) urlEncode = "UTF-8";

    URLConnection conn = new URL(url).openConnection();
    HttpURLConnection hconn = (HttpURLConnection) conn;

    // trust any certification
    if (url.toLowerCase().startsWith("https")) {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
      HttpsURLConnection hsconn = (HttpsURLConnection) hconn;
      hsconn.setSSLSocketFactory(sc.getSocketFactory());
      hsconn.setHostnameVerifier(new TrustAnyHostnameVerifier());
    }

    hconn.setConnectTimeout(timeout);

    if (args != null) {
      for (KVPair pair : args) hconn.setRequestProperty(pair.getKey(), pair.getVal());
    }

    this.cm.setCookies(hconn);
    boolean isPost = method.trim().equalsIgnoreCase("POST");
    if (isPost) hconn.setDoOutput(true);
    hconn.connect();

    // POST request body data
    if (isPost && body != null) {
      String data = "";
      for (KVPair pair : body) {
        data += pair.getKey() + "=";
        data += URLEncoder.encode(pair.getVal(), urlEncode) + "&";
      }
      if (!data.isEmpty()) {
        data = data.substring(0, data.length() - 1);
        hconn.getOutputStream().write(data.getBytes());
        hconn.getOutputStream().flush();
      }
    }
    this.cm.storeCookies(hconn);

    this.rsp = new HttpResponse(hconn);
  }
Example #21
0
  private void createConnection() throws IOException {
    String effectiveUrl = URLUtils.appendParametersToQueryString(url, querystringParams);
    if (connection == null) {
      System.setProperty("http.keepAlive", connectionKeepAlive ? "true" : "false");
      // connection = (HttpURLConnection) new URL(effectiveUrl).openConnection();

      URL url = new URL(effectiveUrl);
      if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        connection = https;
      } else {
        connection = (HttpURLConnection) url.openConnection();
      }
    }
  }
Example #22
0
  private void connectUntrusted() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {}

            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
          }
        };

    // Install the all-trusting trust manager
    // SSLv3 is disabled since SQ 4.5.2 : https://jira.codehaus.org/browse/SONAR-5860
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory untrustedSocketFactory = sc.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid =
        new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };
    URL url = new URL("https://localhost:" + httpsPort + "/sonar/sessions/login");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(true);
    connection.setSSLSocketFactory(untrustedSocketFactory);
    connection.setHostnameVerifier(allHostsValid);

    InputStream input = connection.getInputStream();
    checkCookieFlags(connection);
    try {
      String html = IOUtils.toString(input);
      assertThat(html).contains("<body");
    } finally {
      IOUtils.closeQuietly(input);
    }
  }
  public static String GetData(String strUrl) {
    StringBuilder strResult = new StringBuilder("");

    try {
      URL url = new URL(strUrl);
      HttpURLConnection urlConnection = null;

      if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();

        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        urlConnection = https;
      } else {
        urlConnection = (HttpURLConnection) url.openConnection();
      }

      urlConnection.setRequestMethod("GET");
      urlConnection.setConnectTimeout(10000);
      urlConnection.connect();

      if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader in =
            new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
          strResult.append(inputLine);
        }
      } else {
        strResult.append(urlConnection.getResponseCode());
      }
    } catch (MalformedURLException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    }

    return strResult.toString();
  }
Example #24
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
Example #25
0
  @Test
  public void runStaticResourceServlet() throws Exception {
    URL url = new URL("https://localhost:8443/sample1/hello");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(null, TRUST_ALL_CERTS, null);

    con.setSSLSocketFactory(ssl.getSocketFactory());
    con.setHostnameVerifier(
        new HostnameVerifier() {
          public boolean verify(String s, SSLSession sslSession) {
            return true;
          }
        });

    assertThat(servletContext.getContextPath(), is("/sample1"));
    InputStream is = con.getInputStream();
    OutputStream os = new ByteArrayOutputStream();
    StreamUtils.copyStream(is, os, true);
    assertThat(os.toString(), containsString("Hello from Pax Web!"));
  }
Example #26
0
  /** Make connection to URL and print contents of the URL to standard output */
  public void connect(String urlString) throws IOException {
    URLConnection conn = new URL(urlString).openConnection();
    if (conn instanceof HttpsURLConnection) {
      ((HttpsURLConnection) conn).setHostnameVerifier(this);
    }

    BufferedReader br = null;
    try {
      System.out.println("Connecting to URL: " + urlString);
      conn.connect();
      System.out.println("Contents of the URL (if any) starting from the next line: ");
      br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line = null;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    } finally {
      if (br != null) {
        br.close();
      }
    }
  }
Example #27
0
  /**
   * Creates connection to the specified url. If the protocol is <code>https</code> the connection
   * created doesn't validate any certificates.
   *
   * @param url url to which connection has to be created
   * @param proxy proxy to be used. can be null
   * @return <code>URLConnection</code>. the connection is not yet connected
   * @throws IOException if an I/O exception occurs
   */
  public static URLConnection createUnCertifiedConnection(URL url, Proxy proxy) throws IOException {
    if (sc == null) {
      try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, SSLUtil.DUMMY_TRUST_MANAGERS, new SecureRandom());
        URLUtil.sc = sc;
      } catch (Exception ex) {
        throw new ImpossibleException(ex);
      }
    }

    URLConnection con = proxy == null ? url.openConnection() : url.openConnection(proxy);
    if ("https".equals(url.getProtocol())) {
      HttpsURLConnection httpsCon = (HttpsURLConnection) con;
      httpsCon.setSSLSocketFactory(sc.getSocketFactory());
      httpsCon.setHostnameVerifier(
          new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
              return true;
            }
          });
    }
    return con;
  }
Example #28
0
 /**
  * 创建连接
  *
  * @return
  * @throws ProtocolException
  */
 private HttpURLConnection createConnection(String encoding) throws ProtocolException {
   HttpURLConnection httpURLConnection = null;
   try {
     httpURLConnection = (HttpURLConnection) url.openConnection();
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
   httpURLConnection.setConnectTimeout(this.connectionTimeout); // 连接超时时间
   httpURLConnection.setReadTimeout(this.readTimeOut); // 读取结果超时时间
   httpURLConnection.setDoInput(true); // 可读
   httpURLConnection.setDoOutput(true); // 可写
   httpURLConnection.setUseCaches(false); // 取消缓存
   httpURLConnection.setRequestProperty(
       "Content-type", "application/x-www-form-urlencoded;charset=" + encoding);
   httpURLConnection.setRequestMethod("POST");
   if ("https".equalsIgnoreCase(url.getProtocol())) {
     HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
     husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
     husn.setHostnameVerifier(new TrustAnyHostnameVerifier()); // 解决由于服务器证书问题导致HTTPS无法访问的情况
     return husn;
   }
   return httpURLConnection;
 }
Example #29
0
  @SuppressWarnings("unchecked")
  protected Object execute(final Method method, final Object value) throws QueryException {
    Object result = value;
    URL location = getLocation();
    HttpURLConnection connection = null;

    Serializer<Object> serializerLocal = (Serializer<Object>) this.serializer;

    bytesSent = 0;
    bytesReceived = 0;
    bytesExpected = -1;

    status = 0;
    String message = null;

    try {
      // Clear any properties from a previous response
      responseHeaders.clear();

      // Open a connection
      if (proxy == null) {
        connection = (HttpURLConnection) location.openConnection();
      } else {
        connection = (HttpURLConnection) location.openConnection(proxy);
      }

      connection.setRequestMethod(method.toString());
      connection.setAllowUserInteraction(false);
      connection.setInstanceFollowRedirects(false);
      connection.setUseCaches(false);

      if (connection instanceof HttpsURLConnection && hostnameVerifier != null) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
        httpsConnection.setHostnameVerifier(hostnameVerifier);
      }

      // Set the request headers
      if (result != null) {
        connection.setRequestProperty("Content-Type", serializerLocal.getMIMEType(result));
      }

      for (String key : requestHeaders) {
        for (int i = 0, n = requestHeaders.getLength(key); i < n; i++) {
          if (i == 0) {
            connection.setRequestProperty(key, requestHeaders.get(key, i));
          } else {
            connection.addRequestProperty(key, requestHeaders.get(key, i));
          }
        }
      }

      // Set the input/output state
      connection.setDoInput(true);
      connection.setDoOutput(result != null);

      // Connect to the server
      connection.connect();
      queryListeners.connected(this);

      // Write the request body
      if (result != null) {
        OutputStream outputStream = null;
        try {
          outputStream = connection.getOutputStream();
          serializerLocal.writeObject(result, new MonitoredOutputStream(outputStream));
        } finally {
          if (outputStream != null) {
            outputStream.close();
          }
        }
      }

      // Notify listeners that the request has been sent
      queryListeners.requestSent(this);

      // Set the response info
      status = connection.getResponseCode();
      message = connection.getResponseMessage();

      // Record the content length
      bytesExpected = connection.getContentLength();

      // NOTE Header indexes start at 1, not 0
      int i = 1;
      for (String key = connection.getHeaderFieldKey(i);
          key != null;
          key = connection.getHeaderFieldKey(++i)) {
        responseHeaders.add(key, connection.getHeaderField(i));
      }

      // If the response was anything other than 2xx, throw an exception
      int statusPrefix = status / 100;
      if (statusPrefix != 2) {
        throw new QueryException(status, message);
      }

      // Read the response body
      if (method == Method.GET && status == Query.Status.OK) {
        InputStream inputStream = null;
        try {
          inputStream = connection.getInputStream();
          result = serializerLocal.readObject(new MonitoredInputStream(inputStream));
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
        }
      }

      // Notify listeners that the response has been received
      queryListeners.responseReceived(this);
    } catch (IOException exception) {
      queryListeners.failed(this);
      throw new QueryException(exception);
    } catch (SerializationException exception) {
      queryListeners.failed(this);
      throw new QueryException(exception);
    } catch (RuntimeException exception) {
      queryListeners.failed(this);
      throw exception;
    }

    return result;
  }
  // gets VM home and data page based on boolean parameter
  public static String fetchURL(String username, String password, Boolean getData) {
    String line = "";

    String url = "https://www2.virginmobileusa.com/login/login.do";
    String dataUrl = "https://www2.virginmobileusa.com/myaccount/dataPlanHistory.do";
    try {
      TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              public void checkClientTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}

              public void checkServerTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}
            }
          };
      try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      } catch (Exception e) {
        e.getMessage();
      }

      HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
      ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

      connection.setDoOutput(true);

      String content = "loginRoutingInfo=&min=" + username + "&vkey=" + password + "&submit=submit";

      connection.setFixedLengthStreamingMode(content.length());
      connection.setRequestProperty("Host", "www2.virginmobileusa.com");
      connection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");

      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
      out.write(content);
      out.close();

      InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());

      BufferedReader buff = new BufferedReader(in);

      StringBuilder sb = new StringBuilder();

      while ((line = buff.readLine()) != null) {
        sb.append(line);
      }

      // telephone
      int tel_infoStartIndex = sb.indexOf("id=\"headerimage\"");
      int tel_infoEndIndex = sb.indexOf("<ul class=\"tabnav\">");
      // balance info
      int balance_infoStartIndex = sb.indexOf("id=\"balance_info2b\">");
      int balance_infoEndIndex = sb.indexOf("id=\"payment_strip\"");
      // account activity
      int account_activityStartIndex = sb.indexOf("id=\"account_activity\"");
      int account_activityEndIndex = sb.indexOf("id=\"for_your_phone\"");

      // int mainContentIndex = sb.indexOf("id=\"mainContent\"");
      if (tel_infoStartIndex == -1) {
        line = "";
      } else {
        line = sb.substring(tel_infoStartIndex, tel_infoEndIndex);
      }
      if (balance_infoStartIndex != -1) {

        line += sb.substring(balance_infoStartIndex, balance_infoEndIndex);
      }
      if (account_activityStartIndex != -1) {
        line += sb.substring(account_activityStartIndex, account_activityEndIndex);
      }
      // Now, try to grab data usage
      String cookies = "";
      // 1. Grab and store cookies
      String headerName = null;
      for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase("Set-Cookie")) {
          String cookie = connection.getHeaderField(i);
          cookie = cookie.substring(0, cookie.indexOf(";"));
          String cookieName = cookie.substring(0, cookie.indexOf("="));
          String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
          cookies = cookies + cookieName + "=" + cookieValue + "; ";
        }
      }
      if (getData == true) {
        // get data page
        HttpsURLConnection connection2 = (HttpsURLConnection) new URL(dataUrl).openConnection();
        ((HttpsURLConnection) connection2).setHostnameVerifier(new AllowAllHostnameVerifier());

        connection2.setDoOutput(true);
        connection2.setRequestProperty("Cookie", cookies);
        connection2.connect();
        InputStreamReader in2 = new InputStreamReader((InputStream) connection2.getContent());

        BufferedReader buff2 = new BufferedReader(in2);

        StringBuilder sb2 = new StringBuilder();

        String dataPage;
        while ((dataPage = buff2.readLine()) != null) {
          sb2.append(dataPage);
        }

        int dataContentIndex = sb2.indexOf("<h2>Mobile Web History</h2>");
        if (dataContentIndex == -1) {
          dataPage = "";
        } else {
          dataPage = sb2.substring(dataContentIndex);
          line += ("****************" + dataPage);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      // System.err.println("exception 83");
      // System.err.println(e.getMessage());
      // System.err.println(line);
      return line;
      // rc.put("isValid", "FALSE");
    }
    return line;
  }