List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:com.google.code.maven.plugin.http.client.Request.java
/** * @param httpclient/* www. jav a 2 s.c o m*/ * @param parser * @return * @throws MojoExecutionException * @throws IOException */ public HttpRequestBase buildHttpRequestBase(DefaultHttpClient httpclient, Log log) throws MojoExecutionException, IOException { buildHttpHost(log); // credential if (credentials != null) { // simple authentication httpclient.getCredentialsProvider().setCredentials(// new AuthScope(finalUrl.getHost(), finalUrl.getPort()), // credentials.toUsernamePasswordCredentials()); } if (formCredentials != null) { // form authentication formCredentials.authenticate(httpclient, log); } HttpRequestBase httpRequest = null; if ("get".equalsIgnoreCase(method)) { HttpGet httpGet = new HttpGet(finalUrl.toString()); httpRequest = httpGet; } else if ("post".equalsIgnoreCase(method)) { HttpPost httpPost = new HttpPost(finalUrl.getPath()); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (parameters != null) { for (Parameter parameter : parameters) { nvps.add(parameter.toNameValuePair()); } } httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); httpRequest = httpPost; } else { throw new MojoExecutionException("unknow method " + method); } return httpRequest; }
From source file:fr.norsys.asoape.ws.transport.HttpTransport.java
/** * {@link SoapEnvelope} transport from client to server without response (one way). * /*from ww w . j ava 2s .c o m*/ * @param serviceUrl URL of the service to reach. * @param outgoingEnvelope Outgoing request message. * @throws MarshallingException Whenever a Java To XML mapping error occurs. * @throws IOException Whenever a communication problem occurs. */ public void sendAsync(URL serviceUrl, SoapEnvelope outgoingEnvelope) throws MarshallingException, IOException { // Preparing request HttpPost post = new HttpPost(serviceUrl.toString()); StringWriter writer = new StringWriter(); Marshaller marshaller = bindingContext.createMarshaller(); marshaller.marshall(outgoingEnvelope, writer); String soapMessage = writer.toString(); debug(soapMessage); StringEntity message = new StringEntity(soapMessage, "UTF-8"); message.setContentType("text/xml; charset=utf-8"); post.setEntity(message); HttpParams httpParameters = new BasicHttpParams(); if (connectionTimeout != null) { // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); } if (socketTimeout != null) { // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); } DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); if (hasAuthentication()) { AuthScope authScope = new AuthScope(serviceUrl.getHost(), serviceUrl.getPort()); Credentials credentials = new UsernamePasswordCredentials(username, password); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } httpClient.execute(post); }
From source file:fr.norsys.asoape.ws.transport.HttpTransport.java
/** * {@link SoapEnvelope} transport from client to server and return {@link SoapEnvelope} recognition. * /* w ww.jav a2 s . co m*/ * @param serviceUrl URL of the service to reach. * @param outgoingEnvelope Outgoing request message. * @return Return the incomming response message. * @throws MarshallingException Whenever a Java To XML mapping error occurs. * @throws IOException Whenever a communication problem occurs. */ public SoapEnvelope send(URL serviceUrl, SoapEnvelope outgoingEnvelope) throws MarshallingException, IOException { // Preparing request HttpPost post = new HttpPost(serviceUrl.toString()); StringWriter writer = new StringWriter(); Marshaller marshaller = bindingContext.createMarshaller(); marshaller.marshall(outgoingEnvelope, writer); String soapMessage = writer.toString(); debug(soapMessage); StringEntity message = new StringEntity(soapMessage, "UTF-8"); message.setContentType("text/xml; charset=utf-8"); post.setEntity(message); HttpParams httpParameters = new BasicHttpParams(); if (connectionTimeout != null) { // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); } if (socketTimeout != null) { // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); } ResponseHandler<SoapEnvelope> responseHandler = new SoapResponseHandler(bindingContext); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); if (hasAuthentication()) { AuthScope authScope = new AuthScope(serviceUrl.getHost(), serviceUrl.getPort()); Credentials credentials = new UsernamePasswordCredentials(username, password); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } return httpClient.execute(post, responseHandler); }
From source file:org.opencastproject.workflow.handler.MediaPackagePostOperationHandler.java
/** * {@inheritDoc}//from w w w . j av a 2 s. co m * * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance, * JobContext) */ public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException { // get configuration WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation(); Configuration config = new Configuration(currentOperation); MediaPackage mp = workflowInstance.getMediaPackage(); /* Check if we need to replace the Mediapackage we got with the published * Mediapackage from the Search Service */ if (config.mpFromSearch()) { SearchQuery searchQuery = new SearchQuery(); searchQuery.withId(mp.getIdentifier().toString()); SearchResult result = searchService.getByQuery(searchQuery); if (result.size() != 1) { throw new WorkflowOperationException("Received multiple results for identifier" + "\"" + mp.getIdentifier().toString() + "\" from search service. "); } logger.info("Getting Mediapackage from Search Service"); mp = result.getItems()[0].getMediaPackage(); } logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as " + config.getFormat().name() + " to " + config.getUrl().toString()); try { // serialize MediaPackage to target format String mpStr; if (config.getFormat() == Configuration.Format.JSON) { mpStr = MediaPackageParser.getAsJSON(mp); } else { mpStr = MediaPackageParser.getAsXml(mp); } // Log mediapackge if (config.debug()) { logger.info(mpStr); } // constrcut message body List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("mediapackage", mpStr)); data.addAll(config.getAdditionalFields()); // construct POST HttpPost post = new HttpPost(config.getUrl()); post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding())); // execute POST DefaultHttpClient client = new DefaultHttpClient(); // Handle authentication if (config.authenticate()) { URL targetUrl = config.getUrl().toURL(); client.getCredentialsProvider().setCredentials( new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials()); } HttpResponse response = client.execute(post); // throw Exception if target host did not return 200 int status = response.getStatusLine().getStatusCode(); if ((status >= 200) && (status < 300)) { if (config.debug()) { logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": " + status); } } else if (status == 418) { logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": The target claims to be a teapot. " + "The Reason for this is probably an insane programmer."); } else { throw new WorkflowOperationException( "Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), " + config.getUrl().toString() + " answered with: " + Integer.toString(status)); } } catch (Exception e) { if (e instanceof WorkflowOperationException) { throw (WorkflowOperationException) e; } else { logger.error("Submitting mediapackage failed: {}", e.toString()); throw new WorkflowOperationException(e); } } return createResult(mp, Action.CONTINUE); }
From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java
protected InputStream fetch(ImageUrlRequest imageUrlRequest) throws MalformedURLException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); ImageToLoadUrl imageToLoadUrl = imageUrlRequest.getImageToLoadUrl(); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(imageToLoadUrl.getUsername(), imageToLoadUrl.getPassword())); HttpResponse response = httpClient.execute(new HttpGet(imageToLoadUrl.getUrl())); int statusCode = response.getStatusLine().getStatusCode(); String reason = response.getStatusLine().getReasonPhrase(); if (statusCode > 299) { throw new HttpResponseException(statusCode, reason); }//from w w w. j ava 2 s. c o m BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); return entity.getContent(); }
From source file:net.nightwhistler.pageturner.PageTurnerModule.java
/** * Binds the HttpClient interface to the DefaultHttpClient implementation. * //from w w w .j a va2s . c o m * In testing we'll use a stub. * * @return */ @Provides @Inject public HttpClient getHttpClient(Configuration config) { HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client; if (config.isAcceptSelfSignedCertificates()) { client = new SSLHttpClient(httpParams); } else { client = new DefaultHttpClient(httpParams); } for (CustomOPDSSite site : config.getCustomOPDSSites()) { if (site.getUserName() != null && site.getUserName().length() > 0) { try { URL url = new URL(site.getUrl()); client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(site.getUserName(), site.getPassword())); } catch (MalformedURLException mal) { //skip to the next } } } return client; }
From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java
public void go() { DefaultHttpClient client = null; try {/*ww w . ja va 2 s.co m*/ prepareForResponse(); if (altInput == null) { client = new DefaultHttpClient(); // Set up preemptive Basic Authentication UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0); if (zip) { client.addRequestInterceptor(new GZipRequestInterceptor()); client.addResponseInterceptor(new GZipResponseInterceptor()); } HttpPost post = new HttpPost(url); try { setPostData(post); HttpResponse response = client.execute(post, localcontext); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println( "Error: Web Service response code of: " + response.getStatusLine().getStatusCode()); return; } HttpEntity entity = response.getEntity(); if (entity != null) { parser.parseResponse(ids.size(), entity.getContent()); } } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } else { // Alternate input (typically from a file) for testing try { parser.parseResponse(ids.size(), altInput); } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } } finally { if (client != null) { client.getConnectionManager().shutdown(); } } /* try { parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump"))); } catch (IOException e) { e.printStackTrace(); } */ }