List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java
/** * Independente de Relatorio//from ww w.j av a 2 s. c o m * @param url * @return * @throws IOException * @throws HttpException * @throws NotHTML * @throws TempoExcedido * @throws IOException * @throws HttpException */ public String getContent(String url) throws HttpException, IOException { metodo = new GetMethod(url); metodo.setRequestHeader("user-agent", "Mozilla/5.0"); metodo.setFollowRedirects(true); int status = httpClient.executeMethod(metodo); String type = getContentType(metodo); String location = getLocation(metodo); //Verificar os possveis erros if (status != HttpStatus.SC_OK) { //No foi aceito, ocorreu um erro 500 404 if (status == HttpStatus.SC_NOT_FOUND) { } return ""; } if ((status == HttpStatus.SC_OK) && (type.toUpperCase().indexOf("TEXT/HTML") == -1)) { //No do tipo texto/html return ""; } //Verifica redirecionamento if (location != "") { //System.out.print(url+" to "+location+"\n"); } String conteudoHTML = metodo.getResponseBodyAsString(); return conteudoHTML; }
From source file:edu.unc.lib.dl.ui.service.DjatokaContentService.java
public void streamJP2(String simplepid, String region, String scale, String rotate, String datastream, OutputStream outStream, HttpServletResponse response, int retryServerError) { HttpClient client = new HttpClient(); StringBuilder path = new StringBuilder(applicationPathSettings.getDjatokaPath()); path.append("resolver?url_ver=Z39.88-2004&rft_id=") .append(applicationPathSettings.getFedoraPathWithoutDefaultPort()).append("/objects/") .append(simplepid).append("/datastreams/").append(datastream).append("/content") .append("&svc_id=info:lanl-repo/svc/getRegion&svc_val_fmt=info:ofi/fmt:kev:mtx:jpeg2000&svc.format=image/jpeg") .append("&svc.rotate=").append(rotate).append("&svc.level=").append(scale).append("&svc.region=") .append(region);/*from ww w .j av a 2s .c o m*/ GetMethod method = new GetMethod(path.toString()); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { if (response != null) { response.setHeader("Content-Type", "image/jpeg"); response.setHeader("content-disposition", "inline"); FileIOUtil.stream(outStream, method); } } else { if ((method.getStatusCode() == 500 || method.getStatusCode() == 404) && retryServerError > 0) { this.getMetadata(simplepid, datastream, outStream, response, retryServerError - 1); } else { LOG.error("Unexpected failure: " + method.getStatusLine().toString()); LOG.error("Path was: " + method.getURI().getURI()); } } } catch (ClientAbortException e) { if (LOG.isDebugEnabled()) LOG.debug("User client aborted request to stream jp2 for " + simplepid, e); } catch (Exception e) { LOG.error("Problem retrieving metadata for " + path, e); } finally { method.releaseConnection(); } }
From source file:com.comcast.cats.service.util.HttpClientUtil.java
public static synchronized Object deleteForObject(String uri, Map<String, String> paramMap) { Object responseObject = new Object(); HttpMethod httpMethod = new DeleteMethod(uri); if ((null != paramMap) && (!paramMap.isEmpty())) { httpMethod.setQueryString(getNameValuePair(paramMap)); }//from ww w . ja v a 2 s . c om Yaml yaml = new Yaml(); HttpClient client = new HttpClient(); InputStream responseStream = null; Reader inputStreamReader = null; try { int responseCode = client.executeMethod(httpMethod); if (HttpStatus.SC_OK != responseCode) { logger.error("[ REQUEST ] " + httpMethod.getURI().toString()); logger.error("[ METHOD ] " + httpMethod.getName()); logger.error("[ STATUS ] " + responseCode); } else { logger.trace("[ REQUEST ] " + httpMethod.getURI().toString()); logger.trace("[ METHOD ] " + httpMethod.getName()); logger.trace("[ STATUS ] " + responseCode); } responseStream = httpMethod.getResponseBodyAsStream(); inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF); responseObject = yaml.load(inputStreamReader); } catch (IOException ioException) { ioException.printStackTrace(); } finally { cleanUp(inputStreamReader, responseStream, httpMethod); } return responseObject; }
From source file:jenkins.plugins.oslccm.CMConsumer.java
private static String createTinyUrl(String url) throws IOException { org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); GetMethod gm = new GetMethod("http://tinyurl.com/api-create.php?url=" + url.replace(" ", "%20")); int status = client.executeMethod(gm); if (status == HttpStatus.SC_OK) { return gm.getResponseBodyAsString(); } else {/*from www. j a v a2 s . c om*/ throw new IOException("Error in tinyurl: " + status); } }
From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java
/** GET * * Instantiates HttpClient, prepares it with session cookies, * executes the request and returns the response body. * @throws RailsAppException //from w w w . j a v a 2s .c o m * * @since 0.8.0 */ protected byte[] get() throws HttpException, IOException, RailsAppException { // Response body from the web server byte[] responseBody = null; statusCode = -1; HttpClient client = preparedClient(); // Create the GET method and prepare its headers GetMethod method = new GetMethod(requestURL.toString()); HttpMethod _method = (HttpMethod) method; method = (GetMethod) prepareMethodHeaders(_method); log.debug("GET request URL: " + requestURL.toString()); try { // Execute the method statusCode = client.executeMethod(method); // log the status if (statusCode != HttpStatus.SC_OK) { String errorMessage = "Request failed: " + method.getStatusLine(); log.error(errorMessage); throw new RailsAppException(errorMessage, new String(method.getResponseBody())); } else { log.debug("Status code: " + method.getStatusLine()); // Read the response body responseBody = method.getResponseBody(); // Keep the headers for future usage (render or resource phase) configureHeader(method.getResponseHeaders()); // Get session cookies cookies = client.getState().getCookies(); log.debug("Stored " + cookies.length + " cookies."); } } finally { method.releaseConnection(); } return responseBody; }
From source file:mitm.common.security.ca.handlers.comodo.ApplyCustomClientCert.java
private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException { if (statusCode != HttpStatus.SC_OK) { throw new IOException("Error applying for Custom Client Cert. Message: " + httpMethod.getStatusLine()); }/*from w ww . j av a 2 s . c o m*/ InputStream input = httpMethod.getResponseBodyAsStream(); if (input == null) { throw new IOException("Response body is null."); } /* * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB. */ InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE); String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII); if (logger.isDebugEnabled()) { logger.debug("Response:\r\n" + response); } Map<String, String[]> parameters = NetUtils.parseQuery(response); String errorCodeParam = getValue(parameters, "errorCode"); if (!StringUtils.isEmpty(errorCodeParam)) { errorCode = CustomClientStatusCode.fromCode(errorCodeParam); error = true; errorMessage = getValue(parameters, "errorMessage"); } else { error = false; orderNumber = getValue(parameters, "orderNumber"); collectionCode = getValue(parameters, "collectionCode"); if (StringUtils.isEmpty(orderNumber)) { throw new IOException(new CustomClientCertException("orderNumber is missing.")); } } }
From source file:com.interaction.example.odata.multicompany.ODataMulticompanyITCase.java
@Test public void testGetServiceDocumentBaseUriWithoutTrailingSlash() throws Exception { org.apache.abdera.model.Service service = null; String testBaseUri = baseUri; if (testBaseUri.endsWith("/")) testBaseUri = testBaseUri.substring(0, testBaseUri.length() - 1); GetMethod method = new GetMethod(testBaseUri); try {/*from www . j ava2s . c o m*/ client.executeMethod(method); assertEquals(200, method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_OK) { // read as string for debugging String response = method.getResponseBodyAsString(); System.out.println("Response = " + response); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<org.apache.abdera.model.Service> doc = parser.parse(new StringReader(response)); service = doc.getRoot(); } } catch (IOException e) { fail(e.getMessage()); } finally { method.releaseConnection(); } assertNotNull(service); assertEquals("http://localhost:8080/example/interaction-odata-multicompany.svc/MockCompany001/", service.getBaseUri().toString()); }
From source file:davmail.caldav.TestCaldav.java
public void testGetCalendar() throws IOException { GetMethod method = new GetMethod("/users/" + session.getEmail() + "/calendar/"); httpClient.executeMethod(method);// w w w.ja v a2 s . c om assertEquals(HttpStatus.SC_OK, method.getStatusCode()); }
From source file:com.basus.fins.data.YahooQuote.java
@Override public void run() { if (!quoteParams.isValidParams()) { if (log.isDebugEnabled()) { log.debug("Invalid parameters for quote request. Aborting"); }/* w ww .j ava 2 s .c om*/ return; } int status = 0; try { if (log.isDebugEnabled()) { log.debug("Excuting: " + yahooHost.getHostURL() + "/" + method.getPath() + "?" + method.getQueryString()); } PortfolioUI.setStatus1("Getting index price from internet", 3000); PortfolioUI.setStatus2("Connected to db " + Data.getDbDirectory(), 0); status = client.executeMethod(yahooHost, method); if (HttpStatus.SC_OK == status) { csvResponse.setContent(method.getResponseBody()); notifyNetListeners(QuoteListener.EVENT_TYPE_CHANGED, this); if (log.isDebugEnabled()) { log.debug("Received HTTP Response:\n" + method.getResponseBodyAsString()); } PortfolioUI.setStatus1("Last update: " + HelperUtil.getDateTime(), 0); } else { log.error(yahooHost.getHostURL() + method.getURI() + " returned HTTP status " + status); isException = true; lastEx = new IOException(method.getURI() + " returned HTTP status " + status); } } catch (HttpException e) { isException = true; lastEx = e; log.error(e); } catch (IOException e) { isException = true; lastEx = e; log.error(e); } }
From source file:com.hp.alm.ali.idea.services.AttachmentService.java
public Entity updateAttachmentProperty(String name, EntityRef parent, String propertyName, String propertyValue, boolean silent) { Entity attachment = new Entity("attachment", 0); attachment.setProperty(propertyName, propertyValue); String xml = XMLOutputterFactory.getXMLOutputter() .outputString(new Document(attachment.toElement(Collections.singleton(propertyName)))); MyResultInfo result = new MyResultInfo(); if (restService.put(xml, result, "{0}s/{1}/attachments/{2}", parent.type, parent.id, EntityQuery.encode(name)) != HttpStatus.SC_OK) { if (!silent) { errorService.showException(new RestException(result)); }/*w ww . j a va 2s . com*/ return null; } EntityList list = EntityList.create(result.getBodyAsStream(), true); if (!list.isEmpty()) { Entity entity = list.get(0); entityService.fireEntityLoaded(entity, EntityListener.Event.GET); return entity; } else { return null; } }