List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:com.marklogic.client.tutorial.util.Bootstrapper.java
/** * Programmatic invocation./* w ww. j av a 2 s. co m*/ * @param configServer the configuration server for creating the REST server * @param restServer the specification of the REST server */ public void makeServer(ConfigServer configServer, RESTServer restServer) throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError { DefaultHttpClient client = new DefaultHttpClient(); String host = configServer.getHost(); int configPort = configServer.getPort(); Authentication authType = configServer.getAuthType(); if (authType != null) { List<String> prefList = new ArrayList<String>(); if (authType == Authentication.BASIC) prefList.add(AuthPolicy.BASIC); else if (authType == Authentication.DIGEST) prefList.add(AuthPolicy.DIGEST); else throw new IllegalArgumentException("Unknown authentication type: " + authType.name()); client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList); String configUser = configServer.getUser(); String configPassword = configServer.getPassword(); client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort), new UsernamePasswordCredentials(configUser, configPassword)); } BasicHttpContext context = new BasicHttpContext(); StringEntity content = new StringEntity(restServer.toXMLString()); content.setContentType("application/xml"); HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis"); poster.setEntity(content); HttpResponse response = client.execute(poster, context); //poster.releaseConnection(); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); String statusPhrase = status.getReasonPhrase(); client.getConnectionManager().shutdown(); if (statusCode >= 300) { throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n" + "Please check the server log for detail"); } }
From source file:org.jenkinsci.plugins.appio.service.AppioService.java
/** * @param appName/*from w w w.j av a 2 s. co m*/ * @return AppioAppObject (org.jenkinsci.plugins.appio.model.AppioAppObject) * @throws Exception */ public AppioAppObject createApp(String appName) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); AppioAppObject theAppObject = new AppioAppObject(); try { // App.io Authorization and Content-Type headers String appioAuth = "Basic " + apiKey; httpPost.addHeader("Authorization", appioAuth); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Accept", appio_v1); // Create App.io App object AppioAppObject appioAppObj = new AppioAppObject(); appioAppObj.setName(appName); // We want to exclude all non-annotated fields Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // Construct {"app": ... } message body AppioApp theApp = new AppioApp(); theApp.setApp(appioAppObj); StringEntity postBody = new StringEntity(gson.toJson(theApp), ContentType.create("application/json", "UTF-8")); httpPost.setEntity(postBody); LOGGER.fine("AppioService.createApp() Request: " + gson.toJson(theApp)); // Call App.io REST API to create the new app HttpResponse response = httpClient.execute(httpHost, httpPost); String jsonAppioApp = handler.handleResponse(response); LOGGER.fine("AppioService.createApp() Response: " + jsonAppioApp); // Get JSON data from the HTTP Response AppioApp appioApp = new Gson().fromJson(jsonAppioApp, AppioApp.class); theAppObject = appioApp.getApp(); } catch (Exception e) { throw e; } finally { try { httpClient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return theAppObject; }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
public String httpSubmit(Map<String, String> data) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(MyApp.HTTP_SUBMIT_URL); HttpResponse response = null;// w ww . j av a 2s . c o m String sResponse = ""; HttpParams myHttpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myHttpParams, MyApp.TIMEOUT); HttpConnectionParams.setSoTimeout(myHttpParams, MyApp.TIMEOUT); httpClient.setParams(myHttpParams); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : data.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpClient.execute(httpPost); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { if (sResponse != null) { sResponse = sResponse.trim() + "\n" + line.trim(); } else { sResponse = line; } } Log.i(MyApp.TAG, sResponse); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } httpClient.getConnectionManager().shutdown(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return sResponse.trim(); }
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadImage(String address, boolean persistant) { if (mDB.hasImage(address)) { mDB.updateImageTime(address, new Date().getTime()); return;/* www . j av a2 s.com*/ } try { // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); HttpGet request = new HttpGet(address); request.setHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (entity != null && status.getStatusCode() == 200) { InputStream inputStream = entity.getContent(); // TODO - parse content-length here ByteArrayOutputStream data = new ByteArrayOutputStream(); byte bytes[] = new byte[512]; int count; while ((count = inputStream.read(bytes)) > 0) { data.write(bytes, 0, count); } if (data.size() > 0) { mDB.insertImage(address, new Date().getTime(), persistant, data.toByteArray()); } } } catch (IOException exc) { if (mLog.e()) mLog.e("error downloading image" + address, exc); } }
From source file:revServTest.IoTTestForPOST.java
public String testPost(StringEntity input) { // String result; HttpResponse response = null;/*from w ww. j ava2s . c o m*/ try { DefaultHttpClient httpClient = new DefaultHttpClient(); // HttpPost postRequest = new // HttpPost("http://pc-drotondi7:8080/REVOCATIONSERVICETEST/revocation"); HttpPost postRequest = new HttpPost("http://localhost:2222/revocation"); // StringEntity input = new StringEntity( // readFileAsString("C:/Users/andrisani/Desktop/firstRevocation.xml")); // StringEntity input = new // StringEntity(readFileAsString("C:/Users/andrisani/Desktop/secondRevocation.xml")); // StringEntity input = new // StringEntity(readFileAsString("C:/Users/andrisani/Desktop/secondRevocation.xml")); // StringEntity input = new // StringEntity(readFileAsString("C:/Users/andrisani/Desktop/pendingRevocation.xml")); input.setContentType("application/xml"); postRequest.setEntity(input); response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 409 && response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 400 && response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 404 && response.getStatusLine().getStatusCode() != 500) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // if (response.getStatusLine().getStatusCode() == 409 || response.getStatusLine().getStatusCode() == 201 || response.getStatusLine().getStatusCode() == 400 // || response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 404 || response.getStatusLine().getStatusCode() == 500) { // // result = RevocationOutCome.code; // // } else { // String res = Integer.toString(response.getStatusLine().getStatusCode()); // result = res; // } // return result; return RevocationOutComePost.code; }
From source file:org.meerkat.services.WebServiceApp.java
/** * checkWebAppStatus//from ww w. j ava 2s . c o m */ public final WebAppResponse checkWebAppStatus() { // Set the response at this point to empty in case of no response at all setCurrentResponse(""); int statusCode = 0; // Create a HttpClient MeerkatHttpClient meerkatClient = new MeerkatHttpClient(); DefaultHttpClient httpClient = meerkatClient.getHttpClient(); HttpResponse httpresponse = null; WebAppResponse response = new WebAppResponse(); XMLComparator xmlCompare; response.setResponseWebService(); String responseFromPostXMLRequest; // Get target URL String strURL = this.getUrl(); // Prepare HTTP post HttpPost httpPost = new HttpPost(strURL); StringEntity strEntity = null; try { strEntity = new StringEntity(postXML, "UTF-8"); } catch (UnsupportedEncodingException e3) { log.error("UnsupportedEncodingException: " + e3.getMessage()); } httpPost.setEntity(strEntity); // Set Headers httpPost.setHeader("Content-type", "text/xml; charset=ISO-8859-1"); // Set the SOAP Action if specified if (!soapAction.equalsIgnoreCase("")) { httpPost.setHeader("SOAPAction", this.soapAction); } // Measure the request time Counter c = new Counter(); c.startCounter(); // Get headers // Header[] headers = httpPost.getAllHeaders(); // int total = headers.length; // log.info("\nHeaders"); // for(int i=0;i<total;i++){ // log.info(headers[i]); // } // Execute the request try { httpresponse = httpClient.execute(httpPost); // Set status code statusCode = httpresponse.getStatusLine().getStatusCode(); } catch (Exception e) { log.error("WebService Exception: " + e.getMessage() + " [URL: " + this.getUrl() + "]"); httpClient.getConnectionManager().shutdown(); c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); setCurrentResponse(e.getMessage()); return response; } response.setHttpStatus(statusCode); // Get the response BufferedReader br = null; try { // Read in UTF-8 br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(), "UTF-8")); } catch (IllegalStateException e1) { log.error("IllegalStateException in http buffer: " + e1.getMessage()); } catch (IOException e1) { log.error("IOException in http buffer: " + e1.getMessage()); } String readLine; String responseBody = ""; try { while (((readLine = br.readLine()) != null)) { responseBody += "\n" + readLine; } } catch (IOException e) { log.error("IOException in http response: " + e.getMessage()); } try { br.close(); } catch (IOException e1) { log.error("Closing BufferedReader: " + e1.getMessage()); } response.setHttpTextResponse(responseBody); setCurrentResponse(responseBody); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.getConnectionManager().shutdown(); // Stop the counter c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); if (statusCode != HttpStatus.SC_OK) { log.warn("Httpstatus code: " + statusCode + " | Method failed: " + httpresponse.getStatusLine()); // Set the response to the error if none present if (this.getCurrentResponse().equals("")) { setCurrentResponse(httpresponse.getStatusLine().toString()); } } // Prepare to compare with expected response responseFromPostXMLRequest = responseBody; // Format both request response and response file XML String responseFromPostXMLRequestFormatted = ""; String xmlResponseExpected = ""; XmlFormatter formatter = new XmlFormatter(); try { responseFromPostXMLRequestFormatted = formatter.format(responseFromPostXMLRequest.trim()); xmlResponseExpected = formatter.format(responseXML); } catch (Exception e) { log.error("Error parsing XML: " + e.getMessage()); } try { // Compare the XML response file with the response XML xmlCompare = new XMLComparator(xmlResponseExpected, responseFromPostXMLRequestFormatted); if (xmlCompare.areXMLsEqual()) { response.setContainsWebServiceExpectedResponse(true); } } catch (Exception e) { log.error("Error parsing XML for comparison: " + e.getMessage()); } return response; }
From source file:com.katsu.springframework.security.authentication.HtmlAuthenticationProvider.java
private Collection<? extends GrantedAuthority> doLogin(AbstractAuthenticationToken upat) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = null;/*from w ww .j a va2 s .co m*/ HttpResponse httpResponse = null; HttpEntity entity = null; try { // httpclient.getCredentialsProvider().setCredentials( // new AuthScope(AuthScope.ANY), // new UsernamePasswordCredentials(upat.getPrincipal().toString(), upat.getCredentials().toString())); httpget = new HttpGet(url.toURI().toASCIIString()); httpget.setHeader("Authorization", getAuthString(upat.getPrincipal().toString(), upat.getCredentials().toString())); httpResponse = httpclient.execute(httpget); entity = httpResponse.getEntity(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { logger.trace(httpResponse.getStatusLine().toString()); String body = new java.util.Scanner(new InputStreamReader(entity.getContent())).useDelimiter("\\A") .next(); List<? extends GrantedAuthority> roles = json.deserialize(body, new TypeToken<List<Role>>() { }.getType()); if (roles != null && roles.size() > 0 && roles.get(0).getAuthority() == null) { roles = json.deserialize(body, new TypeToken<List<Role1>>() { }.getType()); } return roles; } else { throw new Exception(httpResponse.getStatusLine().getStatusCode() + " Http code response."); } } catch (Exception e) { if (entity != null) { logger.error(log(entity.getContent()), e); } else { logger.error(e); } throw e; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadFeedHttp(Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems, ArrayList<Enclosure> enclosures) { try {//from w w w. j a va 2s . c om // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); HttpGet request = new HttpGet(feed.mURL); HttpContext httpContext = new BasicHttpContext(); request.setHeader("User-Agent", USER_AGENT); // send etag if we have it if (feedStatus.mETag.length() > 0) { request.setHeader("If-None-Match", feedStatus.mETag); } // send If-Modified-Since if we have it if (feedStatus.mLastModified.getTime() > 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' GMT'", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String formattedTime = dateFormat.format(feedStatus.mLastModified); // If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT request.setHeader("If-Modified-Since", formattedTime); } request.setHeader("Accept-Encoding", "gzip,deflate"); HttpResponse response = client.execute(request, httpContext); if (mLog.d()) mLog.d("http request: " + feed.mURL); if (mLog.d()) mLog.d("http response code: " + response.getStatusLine()); InputStream inputStream = null; StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (entity != null) { inputStream = entity.getContent(); } try { if (entity != null && status.getStatusCode() == 200) { Header encodingHeader = entity.getContentEncoding(); if (encodingHeader != null) { if (encodingHeader.getValue().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } else if (encodingHeader.getValue().equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(inputStream); } } // remove caching attributes to be replaced with new ones feedStatus.mETag = ""; feedStatus.mLastModified.setTime(0); feedStatus.mTTL = 0; boolean success = parseFeed(inputStream, feed, feedStatus, feedItems, enclosures); if (success) { // if the parse was ok, update these attributes // ETag: "6050003-78e5-4981d775e87c0" Header etagHeader = response.getFirstHeader("ETag"); if (etagHeader != null) { if (etagHeader.getValue().length() < MAX_ETAG_LENGTH) { feedStatus.mETag = etagHeader.getValue(); } else { mLog.e("etag length was too big: " + etagHeader.getValue().length()); } } // Last-Modified: Fri, 24 Dec 2010 00:57:11 GMT Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { try { feedStatus.mLastModified = parseRFC822Date(lastModifiedHeader.getValue()); } catch (ParseException exc) { mLog.e("unable to parse date", exc); } } HttpUriRequest currentReq = (HttpUriRequest) httpContext .getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext .getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); mLog.w("loaded redirect from " + request.getURI().toString() + " to " + currentUrl); feedStatus.mLastURL = currentUrl; } } else { if (status.getStatusCode() == 304) { mLog.d("received 304 not modified"); } } } finally { if (inputStream != null) { inputStream.close(); } } } catch (IOException exc) { mLog.e("error downloading feed " + feed.mURL, exc); } }