List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:org.apache.activemq.artemis.tests.integration.rest.util.RestMessageContext.java
public void setUpPush(String pushTarget) throws Exception { String pushLink = this.contextMap.get(KEY_MSG_PUSH); String pushRegXml = "<push-registration>" + "<link rel=\"destination\" href=\"" + this.connection.getTargetUri() + this.getPushLink(pushTarget) + "\"/>" + "</push-registration>"; CloseableHttpResponse response = connection.post(pushLink, "application/xml", pushRegXml); int code = ResponseUtil.getHttpCode(response); try {/* w w w.j ava 2 s .c o m*/ if (code != 201) { System.out.println("Failed to push " + pushRegXml); System.out.println("Location: " + pushLink); throw new Exception("Failed to register push " + ResponseUtil.getDetails(response)); } } finally { response.close(); } }
From source file:org.elasticsearch.test.rest.client.http.HttpResponse.java
HttpResponse(HttpUriRequest httpRequest, CloseableHttpResponse httpResponse) { this.httpRequest = httpRequest; this.statusCode = httpResponse.getStatusLine().getStatusCode(); this.reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); if (httpResponse.getEntity() != null) { try {/* w ww .j a va 2 s .c o m*/ this.body = EntityUtils.toString(httpResponse.getEntity(), HttpRequestBuilder.DEFAULT_CHARSET); } catch (IOException e) { EntityUtils.consumeQuietly(httpResponse.getEntity()); throw new RuntimeException(e); } finally { try { httpResponse.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } else { this.body = null; } }
From source file:edu.washington.iam.tools.WebClient.java
public Element doRestGet(String url, String auth) { closeIdleConnections();/*from w w w . j a v a 2 s . co m*/ // log.debug("do rest get"); Element ele = null; // restclient = new DefaultHttpClient((ClientConnectionManager)connectionManager, new BasicHttpParams()); if (restclient == null) restclient = new DefaultHttpClient((ClientConnectionManager) connectionManager, new BasicHttpParams()); try { // log.debug(" rest get, url: " + url); // log.debug(" auth: " + auth); HttpGet httpget = new HttpGet(url); if (auth != null) httpget.addHeader("Authorization", auth); httpget.addHeader("Accept", "text/xml"); CloseableHttpResponse response = restclient.execute((HttpUriRequest) httpget); log.debug(" rest get, rsp: " + response.getStatusLine().getStatusCode()); // httpget.releaseConnection(); if (response.getStatusLine().getStatusCode() == 404) { // log.error("rest, url not found"); response.close(); return null; } if (response.getStatusLine().getStatusCode() >= 400) { // log.error("rest error: " + response.getStatusLine().getStatusCode() + " = " + response.getStatusLine().getReasonPhrase()); response.close(); throw new WebClientException("rest error"); } HttpEntity entity = response.getEntity(); // null is error - should get something if (entity == null) { response.close(); throw new WebClientException("restclient get exception"); } // parse response text Document doc = documentBuilder.parse(entity.getContent()); ele = doc.getDocumentElement(); response.close(); } catch (Exception e) { log.error("exception " + e); } return ele; }
From source file:edu.washington.iam.tools.WebClient.java
public Element doRestPut(String url, List<NameValuePair> data, String auth) { closeIdleConnections();/*from www . jav a 2s. c om*/ log.debug("do rest put"); Element ele = null; if (restclient == null) restclient = new DefaultHttpClient((ClientConnectionManager) connectionManager, new BasicHttpParams()); try { log.debug(" rest url: " + url); HttpPut httpput = new HttpPut(url); if (auth != null) httpput.addHeader("Authorization", auth); httpput.setEntity(new UrlEncodedFormEntity(data)); CloseableHttpResponse response = restclient.execute(httpput); log.debug("resp: " + response.getStatusLine().getStatusCode() + " = " + response.getStatusLine().getReasonPhrase()); HttpEntity entity = response.getEntity(); // null is error - should get something if (entity == null) { response.close(); throw new WebClientException("restclient post exception"); } // parse response text Document doc = documentBuilder.parse(entity.getContent()); ele = doc.getDocumentElement(); response.close(); } catch (Exception e) { log.error("exception " + e); } return ele; }
From source file:it.polimi.diceH2020.plugin.net.NetworkManager.java
/** * Fetches vm configurations from the web * // ww w .j a va 2s . c om * @return A json object representing the fetched vm configurations */ public JSONArray fetchVmConfigs() { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(vmConfigsEndpoint); CloseableHttpResponse response; String body; JSONParser parser; try { response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != 200) { return null; } else { // Converts response stream into string in order to parse // everything int json body = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); parser = new JSONParser(); response.close(); return ((JSONArray) parser.parse(body)); } } catch (UnsupportedOperationException | ParseException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:controller.NavigatorServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getParameterMap().toString()); String page = request.getParameter("page"); String type = request.getParameter("type"); System.out.println(page);// www .ja v a2 s. c om System.out.println(type); CloseableHttpClient httpClient = HttpClients.createDefault(); String address = "http://127.0.0.1:8080"; HttpPost httpPost; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (type.equalsIgnoreCase("GetPage")) { switch (page) { case "LogIn": address += "/CloudChatUserManagerClient/loginPage.html"; break; case "LogOut": address += "/CloudChatUserManagerClient/logoutConfirm.html"; break; case "LogInSuccess": address += "/CloudChatUserManagerClient/loginSuccessPage.html"; break; case "Register": System.out.println("Got here"); address += "/CloudChatUserManagerClient/registrationPage.html"; break; case "Edit": address += "/CloudChatServer/edit.jsp"; break; case "Delete": address += "/CloudChatServer/delete.jsp"; break; case "ChatHome": address += "/CloudChatServer/chat.jsp"; break; default: address = ""; break; } } else if (type.equalsIgnoreCase("UserManager")) { address += "/CloudChatUserManagerClient/CloudChatUserManagerServlet"; nvps.add(new BasicNameValuePair("action", request.getParameter("action"))); nvps.add(new BasicNameValuePair("userID", request.getParameter("userID"))); nvps.add(new BasicNameValuePair("password", request.getParameter("password"))); } else if (type.equalsIgnoreCase("Server")) { System.out.println("Got here"); address += "/CloudChatServer/chat"; nvps.add(new BasicNameValuePair("userID", request.getParameter("userID"))); nvps.add(new BasicNameValuePair("action", request.getParameter("action"))); nvps.add(new BasicNameValuePair("messageID", request.getParameter("messageID"))); nvps.add(new BasicNameValuePair("message", request.getParameter("message"))); nvps.add(new BasicNameValuePair("category", request.getParameter("category"))); } httpPost = new HttpPost(address); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { System.out.println(httpResponse.getStatusLine()); HttpEntity entity = httpResponse.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; String res = ""; while ((line = reader.readLine()) != null) { res += line; } EntityUtils.consume(entity); response.getWriter().write(res); } finally { httpResponse.close(); } }
From source file:com.addthis.hydra.task.output.HttpOutputWriter.java
@Nonnull private Integer request(String[] endpoints, String body, MutableInt retry) throws IOException { rotation = (rotation + 1) % endpoints.length; String endpoint = endpoints[rotation]; if (retry.getValue() > 0) { log.info("Attempting to send to {}. Retry {}", endpoint, retry.getValue()); }//from ww w. j ava 2s. c om retry.increment(); CloseableHttpResponse response = null; try { HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON); HttpUriRequest request = buildRequest(requestType, endpoint, entity); response = httpClient.execute(request); EntityUtils.consume(response.getEntity()); return response.getStatusLine().getStatusCode(); } finally { if (response != null) { response.close(); } } }
From source file:eu.diacron.crawlservice.app.Util.java
public static JSONArray getwarcsByCrawlid(String crawlid) { JSONArray warcsArray = null;//from w w w .j a va2 s .c om System.out.println("get crawlid"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); /* credsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("diachron", "7nD9dNGshTtficn")); */ 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 { //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/warcs/" + crawlid); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL + 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(); result = result.replace("u'", "'"); result = result.replace("'", "\""); warcsArray = new JSONArray(result); for (int i = 0; i < warcsArray.length(); i++) { System.out.println("url to download: " + warcsArray.getString(i)); } 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 warcsArray; }
From source file:qhindex.controller.SearchAuthorWorksController.java
private String resolvePublisher(String urlCitationWork, String publisherNameIncomplete) throws IOException { String publisher = publisherNameIncomplete; if (urlCitationWork.contains(".pdf") == false) { // Get the header and determine if the resource is in text format (html or plain) // to be able to extract the publisher name final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(AppHelper.connectionTimeOut) .setConnectionRequestTimeout(AppHelper.connectionTimeOut) .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build(); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig) .build();// www . j a v a 2 s . co m HttpHead httpHead = new HttpHead(urlCitationWork); try { CloseableHttpResponse responseHead = httpclient.execute(httpHead); StatusLine statusLineHead = responseHead.getStatusLine(); responseHead.close(); String contentType = responseHead.getFirstHeader("Content-Type").toString().toLowerCase(); if (statusLineHead.getStatusCode() < 300 && contentType.contains("text/html") || contentType.contains("text/plain")) { HttpGet httpGet = new HttpGet(urlCitationWork); CloseableHttpResponse responsePost = httpclient.execute(httpGet); StatusLine statusLine = responsePost.getStatusLine(); if (statusLine.getStatusCode() < 300) { //AppHelper.waitBeforeNewRequest(); BufferedReader br = new BufferedReader( new InputStreamReader((responsePost.getEntity().getContent()))); String content = new String(); String line; while ((line = br.readLine()) != null) { content += line; } int bodyStartIndex = content.indexOf("<body"); if (bodyStartIndex < 0) bodyStartIndex = 0; try { publisherNameIncomplete = formatRegExSpecialCharsInString(publisherNameIncomplete); Pattern pattern = Pattern.compile(publisherNameIncomplete + "(\\w|\\d|-|\\s)+"); Matcher matcher = pattern.matcher(content); if (matcher.find(bodyStartIndex)) { publisher = content.substring(matcher.start(), matcher.end()); } else { publisher = publisherNameIncomplete; } } catch (Exception ex) { Debug.print( "Exception while resolving publisher for citing work - extrating pattern from citation web resource: " + ex.toString()); resultsMsg += "Exception while resolving publisher for citing work - extrating pattern from citation web resource.\n"; } } responsePost.close(); } } catch (IOException ioEx) { Debug.print("Exception while resolving publisher for citing work: " + ioEx.toString()); resultsMsg += "Exception while resolving publisher for citing work.\n"; } } publisher = publisher.trim(); return publisher; }