List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:org.alfresco.maven.plugin.AbstractRefreshWebappMojo.java
/** * Helper method to make a POST request to the Alfresco Webapp * * @param alfrescoTomcatUrl the URL for the webapp we want to post to * @param postData the POST data that should be sent * @param operation information about the operation we are performing *///from www .j ava 2 s .c om private void makePostCall(URL alfrescoTomcatUrl, List<NameValuePair> postData, String operation) { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { // Set up a HTTP POST request to the Alfresco Webapp we are targeting HttpHost targetHost = new HttpHost(alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort(), alfrescoTomcatUrl.getProtocol()); // Set up authentication parameters CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(refreshUsername, refreshPassword)); // Create the HTTP Client we will use to make the call client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Make the call to Refresh the Alfresco Webapp HttpPost httpPost = new HttpPost(alfrescoTomcatUrl.toURI()); response = client.execute(httpPost); if (postData != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8"); httpPost.setEntity(entity); } httpPost.setHeader("Accept-Charset", "iso-8859-1,utf-8"); httpPost.setHeader("Accept-Language", "en-us"); response = client.execute(httpPost); // If no response, no method has been passed if (response == null) { getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg()); return; } // Check if we got a successful response or not int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { getLog().info("Successfull " + operation + " for " + refreshWebappName); } else { String reasonPhrase = response.getStatusLine().getReasonPhrase(); getLog().warn("Failed to " + operation + " for " + refreshWebappName + ". Response status: " + statusCode + ", message: " + reasonPhrase); } } catch (Exception ex) { getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg()); getLog().error("Exception Msg: " + ex.getMessage()); } finally { closeQuietly(response); closeQuietly(client); } }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {// w w w .j av a2 s . c om CloseableHttpClient httpclient = HttpClientProperties.createHttpClient(); try { // Read content of config pipe Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG); Node configNode = configDocument.selectSingleNode("//config"); URL theURL = new URL(configNode.valueOf("url")); if (configNode.valueOf("auth-method").equals("basic")) { HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol()); //Authentication support CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configNode.valueOf("username"), configNode.valueOf("password"))); // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context httpContext = HttpClientContext.create(); httpContext.setCredentialsProvider(credsProvider); httpContext.setAuthCache(authCache); } else if (configNode.valueOf("auth-method").equals("form")) { //Sign in. Cookie will be remembered bij httpclient HttpPost authpost = new HttpPost(configNode.valueOf("auth-url")); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username"))); nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password"))); authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse httpResponse = httpclient.execute(authpost); // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode())); } CloseableHttpResponse response; if (configNode.valueOf("method").equals("post")) { // POST HttpPost httpRequest = new HttpPost(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("put")) { // PUT HttpPut httpRequest = new HttpPut(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("delete")) { //DELETE HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("head")) { //HEAD HttpHead httpRequest = new HttpHead(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("options")) { //OPTIONS HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else { //Default = GET HttpGet httpRequest = new HttpGet(configNode.valueOf("url")); String acceptHeader = configNode.valueOf("accept"); if (!acceptHeader.isEmpty()) { httpRequest.addHeader("accept", configNode.valueOf("accept")); } //Add proxy route if needed HttpClientProperties.setProxy(httpRequest, theURL.getHost()); response = executeRequest(httpRequest, httpclient); } try { contentHandler.startDocument(); int status = response.getStatusLine().getStatusCode(); AttributesImpl statusAttr = new AttributesImpl(); statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status)); contentHandler.startElement("", "response", "response", statusAttr); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); if (entity != null && contentType != null) { //logger.info("Contenttype: " + contentType.getValue()); //Read content into inputstream InputStream inStream = entity.getContent(); // output-type = json means: response is json, convert to xml if (configNode.valueOf("output-type").equals("json")) { //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!! //javax.json contains readers to read from an inputstream StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer, "UTF-8"); JSONObject json = JSONObject.fromObject(writer.toString()); parseJSONObject(contentHandler, json); // output-type = xml means: response is xml, keep it } else if (configNode.valueOf("output-type").equals("xml")) { try { XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml } else if (configNode.valueOf("output-type").equals("jsonld")) { try { Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response! Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback()); Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource((String) nquads, configNode.valueOf("url")); ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inJsonStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml } else if (configNode.valueOf("output-type").equals("rdf")) { try { Any23 runner = new Any23(); DocumentSource source; //If contentType = text/html than convert from html to xhtml to handle non-xml style html! logger.info("Contenttype: " + contentType.getValue()); if (configNode.valueOf("tidy").equals("yes") && contentType.getValue().startsWith("text/html")) { org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8", configNode.valueOf("url")); //TODO UTF-8 should be read from response! RDFCleaner cleaner = new RDFCleaner(); org.jsoup.nodes.Document cleandoc = cleaner.clean(doc); cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); cleandoc.outputSettings() .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); cleandoc.outputSettings().charset("UTF-8"); source = new StringDocumentSource(cleandoc.html(), configNode.valueOf("url"), contentType.getValue()); } else { source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"), contentType.getValue()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inAnyStream)); } catch (Exception e) { throw new OXFException(e); } } else { CharArrayWriter writer = new CharArrayWriter(); IOUtils.copy(inStream, writer, "UTF-8"); contentHandler.characters(writer.toCharArray(), 0, writer.size()); } } } contentHandler.endElement("", "response", "response"); contentHandler.endDocument(); } finally { response.close(); } } finally { httpclient.close(); } } catch (Exception e) { throw new OXFException(e); } }
From source file:com.seyren.core.util.graphite.GraphiteHttpClient.java
private HttpClient createHttpClient() { HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties() .setConnectionManager(createConnectionManager()) .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(graphiteConnectionRequestTimeout) .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build()); // Set auth header for graphite if username and password are provided if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(graphiteUsername, graphitePassword)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); context.setAttribute("preemptive-auth", new BasicScheme()); clientBuilder.addInterceptorFirst(new PreemptiveAuth()); }//from ww w .ja v a2 s . c o m return clientBuilder.build(); }
From source file:org.fao.geonet.utils.AbstractHttpRequest.java
protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException { return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() { @Nullable/* w ww. ja v a 2 s .c o m*/ @Override public Void apply(@Nonnull HttpClientBuilder input) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (credentials != null) { final URI uri = httpMethod.getURI(); HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); credentialsProvider.setCredentials(new AuthScope(hh), credentials); // Preemptive authentication if (isPreemptiveBasicAuth()) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(hh, basicAuth); // Add AuthCache to the execution context httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); } else { input.setDefaultCredentialsProvider(credentialsProvider); } } else { input.setDefaultCredentialsProvider(credentialsProvider); } if (useProxy) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); input.setProxy(proxy); if (proxyCredentials != null) { credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials); } } input.setRedirectStrategy(new LaxRedirectStrategy()); return null; } }, this); }
From source file:org.zalando.stups.tokens.AccessTokenRefresher.java
private AccessToken createToken(final AccessTokenConfiguration tokenConfig) { try {//from w w w .j av a2 s .co m // collect credentials final ClientCredentials clientCredentials = configuration.getClientCredentialsProvider().get(); final UserCredentials userCredentials = configuration.getUserCredentialsProvider().get(); // prepare basic auth credentials final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(configuration.getAccessTokenUri().getHost(), configuration.getAccessTokenUri().getPort()), new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret())); // create a new client that targets our host with basic auth enabled final CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider).build(); final HttpHost host = new HttpHost(configuration.getAccessTokenUri().getHost(), configuration.getAccessTokenUri().getPort(), configuration.getAccessTokenUri().getScheme()); final HttpPost request = new HttpPost(configuration.getAccessTokenUri()); // prepare the request body final List<NameValuePair> values = new ArrayList<NameValuePair>() { { add(new BasicNameValuePair("grant_type", "password")); add(new BasicNameValuePair("username", userCredentials.getUsername())); add(new BasicNameValuePair("password", userCredentials.getPassword())); add(new BasicNameValuePair("scope", joinScopes(tokenConfig.getScopes()))); } }; request.setEntity(new UrlEncodedFormEntity(values)); // enable basic auth for the request final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // execute! final CloseableHttpResponse response = client.execute(host, request, localContext); try { // success status code? final int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { throw AccessTokenEndpointException.from(response); } // get json response final HttpEntity entity = response.getEntity(); final AccessTokenResponse accessTokenResponse = OBJECT_MAPPER .readValue(EntityUtils.toByteArray(entity), AccessTokenResponse.class); // create new access token object final Date validUntil = new Date( System.currentTimeMillis() + (accessTokenResponse.expiresInSeconds * 1000)); return new AccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getTokenType(), accessTokenResponse.getExpiresInSeconds(), validUntil); } finally { response.close(); } } catch (Throwable t) { throw new AccessTokenEndpointException(t.getMessage(), t); } }
From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testKnox674SslCipherSuiteConfig() throws Exception { LOG_ENTER();// w ww. j a va 2 s . c o m String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); String username = "guest"; String password = "guest-password"; String serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); HttpGet request = new HttpGet(serviceUrl); CloseableHttpResponse response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); gateway.stop(); config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })); config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" })); startGatewayServer(); serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; try { client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); client.execute(request, context); fail("Expected SSLHandshakeException"); } catch (SSLHandshakeException e) { // Expected. client.close(); } client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); LOG_EXIT(); }
From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java
private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth);/* w w w. j a v a 2 s .c o m*/ // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside); method.addHeader("Accept", "application/json"); try { HttpResponse httpResponse = httpClient.execute(method, localContext); int resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode != 200) throw new ResponseException( "Unexpected result code " + resultCode + ": " + convertToString(httpResponse)); Object jo = convertToJSON(httpResponse); response.acceptJSONObject(jo); } finally { method.abort(); } }
From source file:SubmitResults.java
public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user, String password, boolean encrypted, String newIdent) { boolean submit_status = false; File tempFile = null;//from w w w. java2 s.c o m // XSLT if ident needs to be changed final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>" + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>" + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">" + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>" + "</xsl:stylesheet>"; //FileBody fb = null; ContentType ct = null; MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); String urlString = null; HttpHost targetHost = null; if (encrypted) { urlString = "https://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 443, "https"); parent.appendToStatus(" Using https"); //credsProvider.setCredentials( // new AuthScope(hostname, 443, "smap", "digest"), // new UsernamePasswordCredentials(user, password)); credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"), new UsernamePasswordCredentials(user, password)); } else { urlString = "http://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 80, "http"); parent.appendToStatus(" Using http (not encrypted)"); credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"), new UsernamePasswordCredentials(user, password)); } CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // get instance file File instanceFile = new File(instanceFilePath); if (!instanceFile.exists()) { parent.appendToStatus(" Error: Submission file " + instanceFilePath + " does not exist"); } else { HttpPost req = new HttpPost(URI.create(urlString)); //req.setHeader("form_status", status); // smap add form_status header tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder, newIdent); // find all files in parent directory /* File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files ignoring invisible files and the submission file List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file files.add(f); } } */ // add the submission file first... /* ct = ContentType.create("text/xml"); //fb = new FileBody(instanceFile, ct); entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath()); //entity.addPart("xml_submission_file", fb); */ /* for (int j = 0; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { ct = ContentType.create("text/xml"); } else if (extension.equals("jpg")) { ct = ContentType.create("image/jpeg"); } else if (extension.equals("3gp")) { ct = ContentType.create("video/3gp"); } else if (extension.equals("3ga")) { ct = ContentType.create("audio/3ga"); } else if (extension.equals("mp4")) { ct = ContentType.create("video/mp4"); } else if (extension.equals("m4a")) { ct = ContentType.create("audio/m4a"); }else if (extension.equals("csv")) { ct = ContentType.create("text/csv"); } else if (f.getName().endsWith(".amr")) { ct = ContentType.create("audio/amr"); } else if (extension.equals("xls")) { ct = ContentType.create("application/vnd.ms-excel"); } else { ct = ContentType.create("application/octet-stream"); parent.appendToStatus(" Info: unrecognised content type for extension " + extension); } //fb = new FileBody(f, ct); //entity.addPart(f.getName(), fb); entity.addBinaryBody(f.getName(), f, ct, f.getName()); parent.appendToStatus(" Info: added file " + f.getName()); } */ //req.setEntity(entity.build()); // prepare response and return uploaded HttpResponse response = null; try { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "smap"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); // Generate Basic scheme object BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); parent.appendToStatus(" Info: submitting to: " + req.getURI().toString()); response = httpclient.execute(targetHost, req, localContext); int responseCode = response.getStatusLine().getStatusCode(); try { // have to read the stream in order to reuse the connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. parent.appendToStatus(" Info: Response code: " + responseCode + " : " + response.getStatusLine().getReasonPhrase()); if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) { parent.appendToStatus(" Error: upload failed: "); } else { submit_status = true; } } catch (Exception e) { e.printStackTrace(); parent.appendToStatus(" Error: Generic Exception. " + e.toString()); } } try { httpclient.close(); } catch (Exception e) { } finally { } if (tempFile != null) { tempFile.delete(); } return submit_status; }
From source file:org.apache.manifoldcf.crawler.connectors.jira.JiraSession.java
private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth);//from ww w. j av a 2s . c om // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside); method.addHeader("Accept", "application/json"); try { HttpResponse httpResponse = httpClient.execute(method, localContext); int resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode != 200) throw new IOException( "Unexpected result code " + resultCode + ": " + convertToString(httpResponse)); Object jo = convertToJSON(httpResponse); response.acceptJSONObject(jo); } finally { method.abort(); } }