List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:com.serena.rlc.provider.jira.client.JiraClient.java
/** * Execute a put request//from ww w.j av a 2 s. c o m * * @param url * @return Response body * @throws JiraClientException */ private String processPut(SessionData session, String restUrl, String url, String putData) throws JiraClientException { String uri = restUrl + url; logger.debug("Start executing JIRA PUT request to url=\"{}\" with payload={}", uri); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(uri); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword()); putRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false)); putRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); putRequest.addHeader(HttpHeaders.ACCEPT, "application/json"); String result = ""; try { putRequest.setEntity(new StringEntity(putData)); HttpResponse response = httpClient.execute(putRequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw createHttpError(response); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuilder sb = new StringBuilder(1024); String output; while ((output = br.readLine()) != null) { sb.append(output); } logger.debug("End executing JIRA PUT request to url=\"{}\" and receive this result={}", uri, sb); return sb.toString(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new JiraClientException("Server not available", e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.jboss.as.test.integration.security.jaas.JAASIdentityCachingTestCase.java
/** * Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the * expected one./*from www. java2 s . co m*/ * * @param webAppURL * @throws Exception */ @Test public void test(@ArquillianResource URL webAppURL) throws Exception { final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1) + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "=" + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8")); final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1)); LOGGER.info("Requesting URL " + greetingUri); final DefaultHttpClient httpClient = new DefaultHttpClient(); try { final HttpGet getCounter = new HttpGet(counterUri); final HttpGet getGreeting = new HttpGet(greetingUri); HttpResponse response = httpClient.execute(getGreeting); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); //check if LoginModule #login() counter is initialized correctly response = httpClient.execute(getCounter); assertEquals("0", EntityUtils.toString(response.getEntity())); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", CustomLoginModule.PASSWORD); httpClient.getCredentialsProvider() .setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials); //make 2 calls to the servlet response = httpClient.execute(getGreeting); assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity())); response = httpClient.execute(getGreeting); assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity())); //There should be only one call to login() method response = httpClient.execute(getCounter); assertEquals("1", EntityUtils.toString(response.getEntity())); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.siberhus.geopoint.restclient.GeoPointRestClient.java
/** * //from w ww. j a v a 2 s. c o m * @param ipAddr * @param format * @return */ public IpInfo query(String ipAddr, Format format) { Assert.notNull("apiKey", apiKey); Assert.notNull("secret", secret); Assert.notNull("ipAddr", ipAddr); Assert.notNull("format", format); MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // should not happen throw new RuntimeException(e); } String formatStr = format == Format.XML ? "xml" : "json"; long timeInSeconds = (long) (System.currentTimeMillis() / 1000); String input = apiKey + secret + timeInSeconds; digest.update(input.getBytes()); String signature = String.format("%032x", new BigInteger(1, digest.digest())); String url = serviceUrl + ipAddr + "?apikey=" + apiKey + "&sig=" + signature + "&format=" + formatStr; log.debug("Calling Quova ip2loc service from URL: {}", url); DefaultHttpClient httpclient = new DefaultHttpClient(); // Create an HTTP GET request HttpGet httpget = new HttpGet(url); // Execute the request httpget.getRequestLine(); HttpResponse response = null; try { response = httpclient.execute(httpget); } catch (IOException e) { throw new HttpRequestException(e); } HttpEntity entity = response.getEntity(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new HttpRequestException(status.getReasonPhrase()); } // Print the response log.debug("Response status: {}", status); StringBuilder responseText = new StringBuilder(); if (entity != null) { try { InputStream inputStream = entity.getContent(); // Process the response BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { responseText.append(line); } bufferedReader.close(); } catch (IOException e) { throw new HttpRequestException(e); } } // shut down the connection manager to ensure // immediate deallocation of all system resources. httpclient.getConnectionManager().shutdown(); IpInfo ipInfo = null; if (format == Format.XML) { JAXBContext context; try { context = JAXBContext.newInstance(IpInfo.class); Unmarshaller um = context.createUnmarshaller(); ipInfo = (IpInfo) um.unmarshal(new StringReader(responseText.toString())); } catch (JAXBException e) { throw new ResultParseException(e); } } else { ObjectMapper mapper = new ObjectMapper(); try { ipInfo = mapper.readValue(new StringReader(responseText.toString()), IpInfoWrapper.class) .getIpInfo(); } catch (IOException e) { throw new ResultParseException(e); } } return ipInfo; }
From source file:org.jboss.as.test.clustering.cluster.ejb.stateful.StatefulFailoverTestCase.java
private void failover(Class<?> beanClass, URL baseURL1, URL baseURL2) throws Exception { DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient(); URI uri1 = StatefulServlet.createURI(baseURL1, MODULE_NAME, beanClass.getSimpleName()); URI uri2 = StatefulServlet.createURI(baseURL2, MODULE_NAME, beanClass.getSimpleName()); try {//from w w w . j a va 2s. co m assertEquals(1, queryCount(client, uri1)); assertEquals(2, queryCount(client, uri1)); assertEquals(3, queryCount(client, uri2)); assertEquals(4, queryCount(client, uri2)); undeploy(DEPLOYMENT_2); assertEquals(5, queryCount(client, uri1)); assertEquals(6, queryCount(client, uri1)); deploy(DEPLOYMENT_2); assertEquals(7, queryCount(client, uri1)); assertEquals(8, queryCount(client, uri1)); assertEquals(9, queryCount(client, uri2)); assertEquals(10, queryCount(client, uri2)); undeploy(DEPLOYMENT_1); assertEquals(11, queryCount(client, uri2)); assertEquals(12, queryCount(client, uri2)); deploy(DEPLOYMENT_1); assertEquals(13, queryCount(client, uri1)); assertEquals(14, queryCount(client, uri1)); assertEquals(15, queryCount(client, uri2)); assertEquals(16, queryCount(client, uri2)); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java
/** * Execute a get request//from w w w . j ava2 s . c o m * * @param jenkinsUrl * @param getPath * @return Response body * @throws JenkinsClientException */ public String processGet(String jenkinsUrl, String getPath) throws JenkinsClientException { String uri = createUrl(jenkinsUrl, getPath); logger.debug("Start executing Jenkins GET request to url=\"{}\"", uri); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(uri); if (getJenkinsUsername() != null && !StringUtils.isEmpty(getJenkinsUsername())) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJenkinsUsername(), getJenkinsPassword()); getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false)); } getRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); getRequest.addHeader(HttpHeaders.ACCEPT, "application/json"); String result = ""; try { HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw createHttpError(response); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuilder sb = new StringBuilder(1024); String output; while ((output = br.readLine()) != null) { sb.append(output); } result = sb.toString(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new JenkinsClientException("Server not available", e); } finally { httpClient.getConnectionManager().shutdown(); } logger.debug("End executing Jenkins GET request to url=\"{}\" and receive this result={}", uri, result); return result; }
From source file:messenger.PlurkApi.java
public String plurkAdd(String url) { PlurkApi p = PlurkApi.getInstance(); if (cookiestore == null) p.login();/*w w w .j av a 2 s . c o m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); if (use_proxy) { HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpclient.setCookieStore(cookiestore); HttpResponse response = null; String responseString = null; try { String content = URLEncoder.encode(url, "UTF-8"); HttpGet httpget = new HttpGet(getApiUri("/Timeline/plurkAdd?" + "api_key=" + API_KEY + "&" + "content=" + content + "&" + "qualifier=" + "says" + "&" + "lang=tr_ch")); response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { cookiestore = httpclient.getCookieStore(); responseString = EntityUtils.toString(response.getEntity()); // pG^O 200 OK ~X // System.out.println(responseString); // } else { System.out.println(response.getStatusLine()); responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); return responseString; }
From source file:com.serena.rlc.provider.artifactory.client.ArtifactoryClient.java
/** * Execute a get request to Artifactory. * * @param path the path for the specific request * @param parameters parameters to send with the query * @return String containing the response body * @throws ArtifactoryClientException//w ww .j a va 2 s. com */ protected String processGet(String path, String parameters) throws ArtifactoryClientException { String uri = createUrl(path, parameters); logger.debug("Start executing Artifactory GET request to url=\"{}\"", uri); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(uri); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getArtifactoryUsername(), getArtifactoryPassword()); getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false)); getRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE); getRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE); getRequest.addHeader("X-Result-Detail", "info, properties"); String result = ""; try { HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) { throw createHttpError(response); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuilder sb = new StringBuilder(1024); String output; while ((output = br.readLine()) != null) { sb.append(output); } result = sb.toString(); } catch (IOException ex) { logger.error(ex.getMessage(), ex); throw new ArtifactoryClientException("Server not available", ex); } finally { httpClient.getConnectionManager().shutdown(); } logger.debug("End executing Artifactory GET request to url=\"{}\" and receive this result={}", uri, result); return result; }
From source file:pl.softech.gw.download.ResourceDownloader.java
public void download(String url, File dir, String fileName) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpclient.execute(httpGet); HttpEntity entity = null;//from ww w . ja v a 2s . c o m BufferedInputStream in = null; InputStream ins = null; BufferedOutputStream out = null; try { StatusLine statusLine = response.getStatusLine(); entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } ins = entity.getContent(); long all = entity.getContentLength(); in = new BufferedInputStream(ins); out = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName))); byte[] buffer = new byte[1024]; int cnt; while ((cnt = in.read(buffer)) >= 0) { out.write(buffer, 0, cnt); fireEvent(new BytesReceivedEvent(cnt, all, fileName)); } } catch (IOException e) { fireEvent(new DownloadErrorEvent(String.format("Error during downloading file %s", fileName), e)); throw e; } finally { if (ins != null) { ins.close(); } if (in != null) { in.close(); } if (out != null) { out.close(); } httpGet.releaseConnection(); httpclient.getConnectionManager().shutdown(); } }
From source file:com.adam.aslfms.service.NPNotifier.java
/** * Connects to Last.fm servers and requests a Now Playing notification of * <code>track</code>. If an error occurs, exceptions are thrown. * /*from w w w . j av a 2 s . c om*/ * @param track * the track to send as notification * @throws BadSessionException * means that a new handshake is needed * @throws TemporaryFailureException * @throws UnknownResponseException * {@link UnknownResponseException} * */ public void notifyNowPlaying(Track track, HandshakeResult hInfo) throws BadSessionException, TemporaryFailureException { Log.d(TAG, "Notifying now playing: " + getNetApp().getName()); Log.d(TAG, getNetApp().getName() + ": " + track.toString()); DefaultHttpClient http = new DefaultHttpClient(); HttpPost request = new HttpPost(hInfo.nowPlayingUri); List<BasicNameValuePair> data = new LinkedList<BasicNameValuePair>(); data.add(new BasicNameValuePair("s", hInfo.sessionId)); data.add(new BasicNameValuePair("a", track.getArtist())); data.add(new BasicNameValuePair("b", track.getAlbum())); data.add(new BasicNameValuePair("t", track.getTrack())); data.add(new BasicNameValuePair("l", Integer.toString(track.getDuration()))); data.add(new BasicNameValuePair("n", track.getTrackNr())); data.add(new BasicNameValuePair("m", track.getMbid())); try { request.setEntity(new UrlEncodedFormEntity(data, "UTF-8")); ResponseHandler<String> handler = new BasicResponseHandler(); String response = http.execute(request, handler); if (response.startsWith("OK")) { Log.i(TAG, "Nowplaying success: " + getNetApp().getName()); } else if (response.startsWith("BADSESSION")) { throw new BadSessionException("Nowplaying failed because of badsession"); } else { throw new TemporaryFailureException("NowPlaying failed weirdly: " + response); } } catch (ClientProtocolException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } catch (IOException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } finally { http.getConnectionManager().shutdown(); } }
From source file:br.cefetrj.sagitarii.teapot.comm.WebClient.java
public String doGet(String action, String parameter) throws Exception { String resposta = "SEM_RESPOSTA"; String mhpHost = gf.getHostURL(); String url = mhpHost + "/" + action + "?" + parameter; DefaultHttpClient httpClient = new DefaultHttpClient(); if (gf.useProxy()) { if (gf.getProxyInfo() != null) { HttpHost httpproxy = new HttpHost(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort()), new UsernamePasswordCredentials(gf.getProxyInfo().getUser(), gf.getProxyInfo().getPassword())); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy); }//from www. j a v a 2 s. c o m } httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); getRequest.addHeader("Content-Type", "plain/text; charset=utf-8"); HttpResponse response = httpClient.execute(getRequest); response.setHeader("Content-Type", "plain/text; charset=UTF-8"); int stCode = response.getStatusLine().getStatusCode(); if (stCode != 200) { System.out.println("Sagitarii nao recebeu meu anuncio. Codigo de erro " + stCode); System.out.println(url); } else { HttpEntity entity = response.getEntity(); InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8"); resposta = convertStreamToString(isr); Charset.forName("UTF-8").encode(resposta); httpClient.getConnectionManager().shutdown(); isr.close(); } return resposta; }