List of usage examples for org.apache.http.auth AuthScope AuthScope
public AuthScope(final String host, final int port)
From source file:com.networkmanagerapp.SettingBackgroundUploader.java
/** * Performs the file upload in the background * @throws FileNotFoundException, IOException, both caught internally. * @param arg0 The intent to run in the background. *///from w w w .ja v a 2 s . c o m @Override protected void onHandleIntent(Intent arg0) { configFilePath = arg0.getStringExtra("CONFIG_FILE_PATH"); key = arg0.getStringExtra("KEY"); value = arg0.getStringExtra("VALUE"); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); try { fos = NetworkManagerMainActivity.getInstance().openFileOutput(this.configFilePath, Context.MODE_PRIVATE); String nameLine = "Name" + " = " + "\"" + this.key + "\"\n"; String valueLine = "Value" + " = " + "\"" + this.value + "\""; fos.write(nameLine.getBytes()); fos.write(valueLine.getBytes()); fos.close(); String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); File f = new File(NetworkManagerMainActivity.getInstance().getFilesDir() + "/" + this.configFilePath); HttpHost targetHost = new HttpHost( PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"), 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpPost httpPost = new HttpPost("http://" + PreferenceManager.getDefaultSharedPreferences(NetworkManagerMainActivity.getInstance()) .getString("ip_preference", "192.168.1.1") + ":1080/cgi-bin/upload.php"); MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(f)); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); Log.d("upload", response.getStatusLine().toString()); } catch (FileNotFoundException e) { Log.e("NETWORK_MANAGER_XU_FNFE", e.getLocalizedMessage()); } catch (IOException e) { Log.e("NETWORK_MANAGER_XU_IOE", e.getLocalizedMessage()); } finally { mNM.cancel(R.string.upload_service_started); stopSelf(); } }
From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java
@Test public void testBasicAuth() throws Exception { URL url = new URL(this.urlStr); DefaultHttpClient httpclient = null; try {/*from w w w. j a va2s. c om*/ String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(user, pass)); HttpGet httpget = new HttpGet(url.toExternalForm()); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.apiwatch.util.IO.java
public static void putAPIData(APIScope scope, String format, String encoding, String location, String username, String password) throws SerializationError, IOException, HttpException { if (URL_RX.matcher(location).matches()) { DefaultHttpClient client = new DefaultHttpClient(); if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username, password)); }/*from w w w . j a v a2s. c o m*/ HttpPost req = new HttpPost(location); StringWriter writer = new StringWriter(); Serializers.dumpAPIScope(scope, writer, format); HttpEntity entity = new StringEntity(writer.toString(), encoding); req.setEntity(entity); req.setHeader("content-type", format); req.setHeader("content-encoding", encoding); HttpResponse response = client.execute(req); client.getConnectionManager().shutdown(); if (response.getStatusLine().getStatusCode() >= 400) { throw new HttpException(response.getStatusLine().getReasonPhrase()); } LOGGER.info("Sent results to URL: " + location); } else { File dir = new File(location); dir.mkdirs(); File file = new File(dir, "api." + format); OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, encoding); Serializers.dumpAPIScope(scope, writer, format); writer.flush(); writer.close(); out.close(); LOGGER.info("Wrote results to file: " + file); } }
From source file:org.jboss.as.test.integration.web.security.authentication.BasicAuthenticationMechanismPicketboxRemovedTestCase.java
/** * Test checks if correct response is returned after the EJB is called from the secured servlet. * * @param url/*w w w .j av a2 s . com*/ * @throws Exception */ @Test public void test(@ArquillianResource URL url) throws Exception { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(USER, PASSWORD)); try (CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider).build()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/"); HttpResponse response = httpclient.execute(httpget); assertNotNull("Response is 'null', we expected non-null response!", response); String text = Utils.getContent(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER)); assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER)); assertTrue("Authentication type different from what we expected!", text.contains("Authentication Type: BASIC")); } }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlStatusById(String crawlid) { String status = ""; System.out.println("get crawlid"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/* w w w . jav a 2 s.c o m*/ //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl/" + crawlid); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL + crawlid); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); String result = ""; BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result += inputLine; } in.close(); // TO-DO should be removed in the future and handle it more gracefully result = result.replace("u'", "'"); result = result.replace("'", "\""); JSONObject crawljson = new JSONObject(result); System.out.println("myObject " + crawljson.toString()); status = crawljson.getString("status"); EntityUtils.consume(response.getEntity()); } catch (JSONException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return status; }
From source file:dk.moerks.ratebeermobile.io.TwitterPoster.java
private HttpResponse postRequest(Context context, String url, List<NameValuePair> parameters) throws NetworkException { // Set up our own HttpClient DefaultHttpClient client = new DefaultHttpClient(new BasicHttpParams()); HttpPost post = new HttpPost(url); // Set RateBeer Mobile as twit source parameters.add(new BasicNameValuePair("source", SOURCE)); // Basic authentication of our Twitter user client.getCredentialsProvider().setCredentials(new AuthScope("api.twitter.com", 80), new UsernamePasswordCredentials(this.name, this.password)); try {//from w w w . j a va2 s .c o m // Send POST request post.setEntity(new UrlEncodedFormEntity(parameters)); return client.execute(post); } catch (UnsupportedEncodingException e) { throw new NetworkException(context, LOGTAG, "Network Error - Cannot build Twitter request", e); } catch (ClientProtocolException e) { throw new NetworkException(context, LOGTAG, "Network Error - Cannot build Twitter request", e); } catch (IOException e) { throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e); } }
From source file:net.netheos.pcsapi.oauth.PasswordSessionManager.java
private synchronized HttpContext getHttpContext(HttpHost host) { ThreadLocal<HttpContext> tlContext = cache.get(host); if (tlContext == null) { tlContext = new ThreadLocal<HttpContext>(); cache.put(host, tlContext);/*ww w .j a v a 2 s. co m*/ } HttpContext context = tlContext.get(); if (context == null) { AuthScope scope = new AuthScope(host.getHostName(), host.getPort()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(scope, usernamePasswordCredentials); context = new BasicHttpContext(); context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); tlContext.set(context); } return context; }
From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurerTests.java
/** * Test ensuring that the {@link AuthScope} is set for the target host. *//*w ww. j a va2s . c o m*/ @Test public void testThatHttpClientWithProxyIsCreatedAndHasCorrectCredentialsProviders() throws Exception { final URI targetHost = new URI("http://test.com"); final HttpClientConfigurer builder = HttpClientConfigurer.create(targetHost); builder.basicAuthCredentials("foo", "password"); builder.withProxyCredentials(URI.create("https://spring.io"), null, null); final Field credentialsProviderField = ReflectionUtils.findField(HttpClientConfigurer.class, "credentialsProvider"); ReflectionUtils.makeAccessible(credentialsProviderField); CredentialsProvider credentialsProvider = (CredentialsProvider) credentialsProviderField.get(builder); Assert.assertNotNull(credentialsProvider.getCredentials(new AuthScope("test.com", 80))); Assert.assertNull(credentialsProvider.getCredentials(new AuthScope("spring.io", 80))); }
From source file:io.uploader.drive.config.proxy.Proxy.java
@Override public CredentialsProvider getCredentialsProvider() { if (isActive()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(getHost(), getPort()), new UsernamePasswordCredentials(getUsername(), getPassword())); return credsProvider; } else {//from w w w .jav a 2 s. c om return null; } }
From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java
/** * Configures the {@link HttpClientBuilder} with a proxy host. If the * {@code proxyUsername} and {@code proxyPassword} are not {@code null} * then a {@link CredentialsProvider} is also configured for the proxy host. * * @param proxyUri Must not be null and must be configured with a scheme (http or https). * @param proxyUsername May be null//ww w . j a v a 2 s.co m * @param proxyPassword May be null * @return a reference to {@code this} to enable chained method invocation */ public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) { Assert.notNull(proxyUri, "The proxyUri must not be null."); Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty."); httpClientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme())); if (proxyUsername != null && proxyPassword != null) { final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } return this; }