List of usage examples for org.apache.commons.httpclient HttpClient executeMethod
public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException
From source file:de.mpg.escidoc.services.common.util.Util.java
public static String getConeSession() throws Exception { long now = new Date().getTime(); if (coneSession == null || (now - coneSessionTimestamp) > 1000 * 60 * 30) { String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url"); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(queryUrl); try {/* w w w . j a v a 2 s .c o m*/ client.executeMethod(method); } catch (Exception e) { logger.warn("Error while retrieving CoNE session", e); return null; } Header[] cookies = method.getResponseHeaders("Set-Cookie"); if (cookies != null && cookies.length > 0) { for (Header cookie : cookies) { if (cookie.getValue().startsWith("JSESSIONID=")) { int end = cookie.getValue().indexOf(";", 11); if (end >= 0) { coneSession = cookie.getValue().substring(11, end); coneSessionTimestamp = now; logger.info("Refreshing CoNE session: " + coneSession); return coneSession; } } } } return null; } else { return coneSession; } }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Execute webdav request.//from ww w .j a va 2 s . c o m * * @param httpClient http client instance * @param method webdav method * @return Responses enumeration * @throws IOException on error */ public static MultiStatusResponse[] executeMethod(HttpClient httpClient, DavMethodBase method) throws IOException { MultiStatusResponse[] responses = null; try { int status = httpClient.executeMethod(method); // need to follow redirects (once) on public folders if (isRedirect(status)) { method.releaseConnection(); URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true); checkExpiredSession(targetUri.getQuery()); method.setURI(targetUri); status = httpClient.executeMethod(method); } if (status != HttpStatus.SC_MULTI_STATUS) { throw buildHttpException(method); } responses = method.getResponseBodyAsMultiStatus().getResponses(); } catch (DavException e) { throw new IOException(e.getMessage()); } finally { method.releaseConnection(); } return responses; }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Execute webdav request.// w ww. ja va 2 s.c om * * @param httpClient http client instance * @param method webdav method * @return Responses enumeration * @throws IOException on error */ public static MultiStatusResponse[] executeMethod(HttpClient httpClient, ExchangeDavMethod method) throws IOException { MultiStatusResponse[] responses = null; try { int status = httpClient.executeMethod(method); // need to follow redirects (once) on public folders if (isRedirect(status)) { method.releaseConnection(); URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true); checkExpiredSession(targetUri.getQuery()); method.setURI(targetUri); status = httpClient.executeMethod(method); } if (status != HttpStatus.SC_MULTI_STATUS) { throw buildHttpException(method); } responses = method.getResponses(); } finally { method.releaseConnection(); } return responses; }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Execute test method from checkConfig, with proxy credentials, but without Exchange credentials. * * @param httpClient Http client instance * @param method Http method//from w ww. ja va 2 s. c om * @return Http status * @throws IOException on error */ public static int executeTestMethod(HttpClient httpClient, GetMethod method) throws IOException { // do not follow redirects in expired sessions method.setFollowRedirects(false); int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) { resetMethod(method); LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM"); addNTLM(httpClient); status = httpClient.executeMethod(method); } return status; }
From source file:ke.go.moh.oec.adt.Daemon.java
private static boolean sendMessage(String url, String filename) { int returnStatus = HttpStatus.SC_CREATED; HttpClient httpclient = new HttpClient(); HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager(); connectionManager.getParams().setSoTimeout(120000); PostMethod httpPost = new PostMethod(url); RequestEntity requestEntity;/* w ww . j av a2 s . c o m*/ try { FileInputStream message = new FileInputStream(filename); Base64InputStream message64 = new Base64InputStream(message, true, -1, null); requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream"); } catch (FileNotFoundException e) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e); return false; } httpPost.setRequestEntity(requestEntity); try { httpclient.executeMethod(httpPost); returnStatus = httpPost.getStatusCode(); } catch (SocketTimeoutException e) { returnStatus = HttpStatus.SC_REQUEST_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out. Not retrying.", e); } catch (HttpException e) { returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception. Not retrying.", e); } catch (ConnectException e) { returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable. Not retrying.", e); } catch (UnknownHostException e) { returnStatus = HttpStatus.SC_NOT_FOUND; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found. Not retrying.", e); } catch (IOException e) { returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception. Not retrying.", e); } finally { httpPost.releaseConnection(); } return returnStatus == HttpStatus.SC_OK; }
From source file:net.bioclipse.opentox.api.Dataset.java
public static void setMetadata(String datasetURI, String predicate, String value) throws Exception { HttpClient client = new HttpClient(); PutMethod method = new PutMethod(normalizeURI(datasetURI) + "metadata"); HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() { {// w w w .ja va2 s .co m put("Content-type", "text/n3"); } }); String triples = "<" + datasetURI + "> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> " + "<http://www.opentox.org/api/1.1#Dataset> .\n" + "<" + datasetURI + "> <" + predicate + "> " + value + " ."; System.out.println("Triples:\n" + triples); method.setRequestBody(triples); client.executeMethod(method); int status = method.getStatusCode(); if (status == 200) { // OK, that was quick! String response = method.getResponseBodyAsString(); System.out.println("Set value response: " + response); } else if (status == 202) { // OK, we got a task... let's wait until it is done String task = method.getResponseBodyAsString(); Thread.sleep(1000); // let's be friendly, and wait 1 sec TaskState state = Task.getState(task); while (!state.isFinished()) { Thread.sleep(3000); // let's be friendly, and wait 3 sec state = Task.getState(task); if (state.isRedirected()) { task = state.getResults(); } } // OK, it should be finished now String dataset = state.getResults(); } else { throw new BioclipseException("Status : " + status); } method.releaseConnection(); }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Get Http Status code for the given URL * * @param httpClient httpClient instance * @param url url string/*w w w . j ava 2 s. co m*/ * @return HttpStatus code */ public static int getHttpStatus(HttpClient httpClient, String url) { int status = 0; HttpMethod testMethod = new GetMethod(url); testMethod.setDoAuthentication(false); try { status = httpClient.executeMethod(testMethod); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } finally { testMethod.releaseConnection(); } return status; }
From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java
/** * Queries an eSciDoc instance/*from w w w.j av a 2 s . com*/ * * @param url * @param query * @param adminUserName * @param adminPassword * @param frameworkUrl * @return */ public static Document queryFramework(String url, String query, String adminUserName, String adminPassword, String frameworkUrl) { try { DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod getMethod = new GetMethod(url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))); System.out.println("Querying <" + url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))); client.executeMethod(getMethod); if (getMethod.getStatusCode() == 200) { document = documentBuilder.parse(getMethod.getResponseBodyAsStream()); } else { System.out.println("Error querying: Status " + getMethod.getStatusCode() + "\n" + getMethod.getResponseBodyAsString()); } return document; } catch (Exception e) { try { System.out.println("Error querying Framework <" + url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")) + ">"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } return null; }
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadResource(String url, String extra, String username, String password, String resourcepath) {//from w w w.j a v a 2 s . co m String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000); client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); File input = new File(resourcepath); PutMethod put = new PutMethod(url); put.setDoAuthentication(true); //put.addRequestHeader("Content-type", "application/zip"); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "application/zip"); put.setRequestEntity(entity); // Execute the request try { int result = client.executeMethod(put); output = result + ": " + put.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); } return output; }
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadSld(String url, String extra, String username, String password, String resourcepath) { System.out.println("loadSld url:" + url); System.out.println("path:" + resourcepath); String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000);//ww w.j av a 2s .c o m client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); client.getParams().setAuthenticationPreemptive(true); File input = new File(resourcepath); PutMethod put = new PutMethod(url); put.setDoAuthentication(true); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "application/vnd.ogc.sld+xml"); put.setRequestEntity(entity); // Execute the request try { int result = client.executeMethod(put); output = result + ": " + put.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); } return output; }