List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:com.truebanana.http.HTTPRequest.java
private HttpURLConnection buildURLConnection() { try {//ww w . j av a 2 s . c om Uri.Builder builder = Uri.parse(url).buildUpon(); Iterator<Map.Entry<String, String>> iterator = queryParameters.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> pair = (Map.Entry) iterator.next(); builder.appendQueryParameter(pair.getKey(), pair.getValue()); } URL u = new URL(builder.build().toString()); Proxy proxy = Proxy.NO_PROXY; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { String host = System.getProperty("http.proxyHost"); if (host != null && !host.isEmpty()) { String port = System.getProperty("http.proxyPort"); if (port != null && !port.isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.parseInt(port))); } } } HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection(proxy); urlConnection.setRequestMethod(requestMethod.name()); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(connectTimeout); urlConnection.setReadTimeout(readTimeout); switch (requestMethod) { case POST: case PUT: urlConnection.setDoOutput(true); break; default: case GET: case DELETE: urlConnection.setDoOutput(false); break; } return urlConnection; } catch (MalformedURLException e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid URL."); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid URL."); } }
From source file:com.foundstone.certinstaller.CertInstallerActivity.java
/** * Tests the certificate chain by making a connection with or without the * proxy to the specified URL//from www. j a va 2 s .c o m * * @param urlString * @param proxyIP * @param proxyPort */ private void testCertChain(final String urlString, final String proxyIP, final String proxyPort) { mCaCertInstalled = false; mSiteCertInstalled = false; if (TextUtils.isEmpty(urlString)) { Toast.makeText(getApplicationContext(), "URL is not set", Toast.LENGTH_SHORT).show(); Log.d(TAG, "URL is not set"); return; } pd = ProgressDialog.show(CertInstallerActivity.this, "Testing the cert chain", "", true, false, null); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Log.d(TAG, "[+] Starting HTTPS request..."); HttpsURLConnection urlConnection = null; try { Log.d(TAG, "[+] Set URL..."); URL url = new URL("https://" + urlString); Log.d(TAG, "[+] Open Connection..."); // The user could have ProxyDroid running if (!TextUtils.isEmpty(proxyIP) && !TextUtils.isEmpty(proxyPort)) { Log.d(TAG, "[+] Using proxy " + proxyIP + ":" + proxyPort); Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyIP, Integer.parseInt(proxyPort))); urlConnection = (HttpsURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpsURLConnection) url.openConnection(); } urlConnection.setReadTimeout(15000); Log.d(TAG, "[+] Get the input stream..."); InputStream in = urlConnection.getInputStream(); Log.d(TAG, "[+] Create a buffered reader to read the response..."); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final StringBuilder builder = new StringBuilder(); String line = null; Log.d(TAG, "[+] Read all of the return...."); while ((line = reader.readLine()) != null) { builder.append(line); } mResult = builder.toString(); Log.d(TAG, mResult); // If everything passed we set these both to true mCaCertInstalled = true; mSiteCertInstalled = true; // Catch when the CA doesn't exist // Error: javax.net.ssl.SSLHandshakeException: // java.security.cert.CertPathValidatorException: Trust // anchor for certification path not found } catch (SSLHandshakeException e) { e.printStackTrace(); // Catch when the hostname does not verify // Line 224ish // http://source-android.frandroid.com/libcore/luni/src/main/java/libcore/net/http/HttpConnection.java // http://docs.oracle.com/javase/1.4.2/docs/api/javax/net/ssl/HostnameVerifier.html#method_detail } catch (IOException e) { // Found the CA cert installed but not the site cert mCaCertInstalled = true; e.printStackTrace(); } catch (Exception e) { Log.d(TAG, "[-] Some other exception: " + e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { pd.dismiss(); if (mCaCertInstalled && !mSiteCertInstalled) { Log.d(TAG, Boolean.toString(mCaCertInstalled)); Toast.makeText(getApplicationContext(), "Found the CA cert installed", Toast.LENGTH_SHORT) .show(); setCaTextInstalled(); setSiteTextNotInstalled(); setFullTextNotInstalled(); } else if (mCaCertInstalled && mSiteCertInstalled) { Toast.makeText(getApplicationContext(), "Found the CA and Site certs installed", Toast.LENGTH_SHORT).show(); setCaTextInstalled(); setSiteTextInstalled(); setFullTextInstalled(); } else { Toast.makeText(getApplicationContext(), "No Certificates were found installed", Toast.LENGTH_SHORT).show(); setCaTextNotInstalled(); setSiteTextNotInstalled(); setFullTextNotInstalled(); } super.onPostExecute(result); } }.execute(); }
From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java
@Override public void setProxy(String proxyhost, int proxyport) { if (StringUtils.isNotBlank(proxyhost)) { okHttpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport))); okHttpClient.setSslSocketFactory(sslSocketFactory); } else {//from ww w . j a v a 2s. c om // Set proxy to direct okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setProxy(Proxy.NO_PROXY); } }
From source file:com.microsoft.azure.servicebus.samples.queueswithproxy.QueuesWithProxy.java
public static int runApp(String[] args, Function<String, Integer> run) { try {/*from ww w .j a v a2 s . c o m*/ String connectionString; String proxyHostName; String proxyPortString; int proxyPort; // Add command line options and create parser Options options = new Options(); options.addOption(new Option("c", true, "Connection string")); options.addOption(new Option("n", true, "Proxy hostname")); options.addOption(new Option("p", true, "Proxy port")); CommandLineParser clp = new DefaultParser(); CommandLine cl = clp.parse(options, args); // Pull variables from command line options or environment variables connectionString = getOptionOrEnv(cl, "c", SB_SAMPLES_CONNECTIONSTRING); proxyHostName = getOptionOrEnv(cl, "n", SB_SAMPLES_PROXY_HOSTNAME); proxyPortString = getOptionOrEnv(cl, "p", SB_SAMPLES_PROXY_PORT); // Check for bad input if (StringUtil.isNullOrEmpty(connectionString) || StringUtil.isNullOrEmpty(proxyHostName) || StringUtil.isNullOrEmpty(proxyPortString)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("run jar with", "", options, "", true); return 2; } if (!NumberUtils.isCreatable(proxyPortString)) { System.err.println("Please provide a numerical value for the port"); } proxyPort = Integer.parseInt(proxyPortString); // ProxySelector set up for an HTTP proxy final ProxySelector systemDefaultSelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (uri != null && uri.getHost() != null && uri.getHost().equalsIgnoreCase(proxyHostName)) { List<Proxy> proxies = new LinkedList<>(); proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort))); return proxies; } return systemDefaultSelector.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } systemDefaultSelector.connectFailed(uri, sa, ioe); } }); return run.apply(connectionString); } catch (Exception e) { System.out.printf("%s", e.toString()); return 3; } }
From source file:com.nike.cerberus.module.CerberusModule.java
@Provides @Singleton/*from ww w. j a v a 2 s . com*/ public Proxy proxy() { final Proxy.Type type = proxyDelegate.getProxyType(); if (type == Proxy.Type.DIRECT) { return Proxy.NO_PROXY; } final String host = proxyDelegate.getProxyHost(); final Integer port = proxyDelegate.getProxyPort(); if (StringUtils.isBlank(host) || port == null) { logger.warn("Invalid proxy settings, ignoring..."); return Proxy.NO_PROXY; } return new Proxy(type, new InetSocketAddress(host, port)); }
From source file:gobblin.source.extractor.extract.google.GoogleCommon.java
/** * Provides HttpTransport. If both proxyUrl and postStr is defined, it provides transport with Proxy. * @param proxyUrl Optional.//from ww w.j a v a 2s . c o m * @param portStr Optional. String type for port so that user can easily pass null. (e.g: state.getProp(key)) * @return * @throws NumberFormatException * @throws GeneralSecurityException * @throws IOException */ public static HttpTransport newTransport(String proxyUrl, String portStr) throws NumberFormatException, GeneralSecurityException, IOException { if (!StringUtils.isEmpty(proxyUrl) && !StringUtils.isEmpty(portStr)) { return new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore()) .setProxy( new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(portStr)))) .build(); } return GoogleNetHttpTransport.newTrustedTransport(); }
From source file:com.irccloud.android.GingerbreadImageProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/*from w ww. ja v a 2s . c om*/ } URL url = new URL(request.getRequestLine().getUri()); HttpURLConnection conn = null; Proxy proxy = null; String host = null; int port = -1; if (Build.VERSION.SDK_INT < 11) { Context ctx = IRCCloudApplication.getInstance().getApplicationContext(); if (ctx != null) { host = android.net.Proxy.getHost(ctx); port = android.net.Proxy.getPort(ctx); } } else { host = System.getProperty("http.proxyHost", null); try { port = Integer.parseInt(System.getProperty("http.proxyPort", "8080")); } catch (NumberFormatException e) { port = -1; } } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { InetSocketAddress proxyAddr = new InetSocketAddress(host, port); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); } if (url.getProtocol().toLowerCase().equals("https")) { conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } else { conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setUseCaches(true); if (!isRunning) return; try { client.getOutputStream().write( ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes()); if (conn.getResponseCode() == 200 && conn.getInputStream() != null) { byte[] buff = new byte[8192]; int readBytes; while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } finally { client.close(); } conn.disconnect(); stop(); }
From source file:org.zaproxy.zapmavenplugin.ProcessZAP.java
/** * execute the whole shabang//from ww w . j a va 2s . c o m * * @throws MojoExecutionException */ public void execute() throws MojoExecutionException { if (skip) { getLog().info("Skipping zap exection"); return; } try { zapClientAPI = getZapClient(); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(zapProxyHost, zapProxyPort)); if (spiderURL) { getLog().info("Spider the site [" + targetURL + "]"); spiderURL(targetURL); } else { getLog().info("skip spidering the site [" + targetURL + "]"); } if (scanURL) { getLog().info("Scan the site [" + targetURL + "]"); scanURL(targetURL); } else { getLog().info("skip scanning the site [" + targetURL + "]"); } // filename to share between the session file and the report file String fileName = ""; if (saveSession) { fileName = createTempFilename("ZAP", ""); zapClientAPI.core.saveSession(fileName); } else { getLog().info("skip saveSession"); } if (reportAlerts) { // reuse fileName of the session file if ((fileName == null) || (fileName.length() == 0)) fileName = createTempFilename("ZAP", ""); String fileName_no_extension = FilenameUtils.concat(reportsDirectory, fileName); try { String alerts = getAllAlerts(true); JSON jsonObj = JSONSerializer.toJSON(alerts); writeXml(fileName_no_extension, jsonObj); writeHtmlReport(fileName_no_extension); if (JSON_FORMAT.equals(format)) { writeJson(fileName_no_extension, jsonObj); } else if (NONE_FORMAT.equals(format)) { getLog().info("Only XML report will be generated"); } else { getLog().info( "This format is not supported [" + format + "] ; please choose 'none' or 'json'"); } } catch (Exception e) { getLog().error(e.toString()); e.printStackTrace(); } } } catch (Exception e) { getLog().error(e.toString()); throw new MojoExecutionException("Processing with ZAP failed", e); } finally { if (shutdownZAP && (zapClientAPI != null)) { try { getLog().info("Shutdown ZAProxy"); zapClientAPI.core.shutdown(); } catch (Exception e) { getLog().error(e.toString()); e.printStackTrace(); } } else { getLog().info("No shutdown of ZAP"); } } }
From source file:net.sf.keystore_explorer.utilities.net.PacProxySelector.java
private Proxy parsePacProxy(String pacProxy) { /*//from w ww.ja va2 s. c o m * PAC formats: * * DIRECT Connections should be made directly, without any proxies. * * PROXY host:port The specified proxy should be used. * * SOCKS host:port The specified SOCKS server should be used. * * Where port is not supplied use port 80 */ if (pacProxy.equals("DIRECT")) { return Proxy.NO_PROXY; } String[] split = pacProxy.split(" ", 0); if (split.length != 2) { return null; } String proxyTypeStr = split[0]; String address = split[1]; Proxy.Type proxyType = null; if (proxyTypeStr.equals("PROXY")) { proxyType = Proxy.Type.HTTP; } else if (proxyTypeStr.equals("SOCKS")) { proxyType = Proxy.Type.SOCKS; } if (proxyType == null) { return null; } split = address.split(":", 0); String host = null; int port = 80; if (split.length == 1) { host = split[0]; } else if (split.length == 2) { host = split[0]; try { port = Integer.parseInt(split[1]); } catch (NumberFormatException ex) { return null; } } else { return null; } return new Proxy(proxyType, new InetSocketAddress(host, port)); }