List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode
public abstract int getStatusCode();
From source file:com.yahoo.flowetl.services.http.BaseHttpCaller.java
/** * Attempts to call the given method using the given client and will attempt * this repeatedly up to the max redirect amount. If no redirect location is * found a http exception will be propagated upwards. Otherwise for * non-redirect codes this method will stop. This function is recursively * called.// w w w .j ava 2 s.c o m * * @throws HttpException * @throws IOException */ private void handleRedirects(final HttpClient client, final HttpMethod method, final int curRedirAm, final int maxRedirAm) throws HttpException, IOException { if (logger.isEnabled(Level.DEBUG)) { logger.log(Level.DEBUG, "Executing " + method + " redir count = " + curRedirAm + " of " + maxRedirAm + " possible redirects "); } // exec and see what happened client.executeMethod(method); int code = method.getStatusCode(); if (logger.isEnabled(Level.DEBUG)) { logger.log(Level.DEBUG, "Executing " + method + " got status code " + code + ""); } // supposed redirect codes // everything else will just stop this function if (REDIR_CODES.contains(code) == false) { return; } // die or continue? if (curRedirAm < maxRedirAm) { // ok to try to find it Header locationHeader = method.getResponseHeader(REDIR_HEADER); String redirLoc = null; if (locationHeader != null) { redirLoc = locationHeader.getValue(); } // cleanup and see if we can use it... redirLoc = StringUtils.trim(redirLoc); if (StringUtils.isEmpty(redirLoc) == false) { // reset uri URI nUri = new URI(redirLoc, false); method.setURI(nUri); if (logger.isEnabled(Level.DEBUG)) { logger.log(Level.DEBUG, "Attempting redirect " + (curRedirAm + 1) + " due to status code " + code + " to location " + nUri); } handleRedirects(client, method, curRedirAm + 1, maxRedirAm); } else { // failure at finding header throw new HttpException("Unable to execute " + method + " - no " + REDIR_HEADER + " header found to redirect to during redirect " + curRedirAm); } } else { // max redirects done throw new HttpException("Unable to execute " + method + " after attempting " + curRedirAm + " redirects of " + maxRedirAm + " attempts"); } }
From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java
private HTTPResponse convertResponse(HttpMethod method) { Headers headers = new Headers(); for (Header header : method.getResponseHeaders()) { headers = headers.add(header.getName(), header.getValue()); }//from w ww . j av a 2s . co m InputStream stream = null; HTTPResponse response; try { stream = getInputStream(method); StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()), Status.valueOf(method.getStatusCode()), method.getStatusText()); response = responseCreator.createResponse(line, headers, stream); } finally { if (stream == null) { method.releaseConnection(); } } return response; }
From source file:it.haefelinger.flaka.util.HttpUpload.java
protected boolean exec(HttpMethod meth) { HttpClient client;/* w w w .j a v a 2 s.co m*/ boolean rc = false; /* exec http method */ try { client = new HttpClient(); settimeout(client); setcred(client); client.executeMethod(meth); rc = (meth.getStatusCode() / 100) == 2; if (rc == false) { setError(meth.getStatusLine().toString()); } } catch (java.net.UnknownHostException ex) { set("errmsg", "unable to resolve host `" + ex.getMessage() + "'."); } catch (Exception ex) { setError(ex.getClass().getName() + " " + ex.getMessage()); if (this.debug) { System.err.println("*** excepting seen while uploading .."); ex.printStackTrace(System.err); System.err.println("<<*>>"); } } return rc; }
From source file:it.infn.ct.aleph_portlet.java
public static int getNumRec(String date, int jrec, int num_rec) { HttpClient client = new HttpClient(); HttpMethod method = callAPIOAR(date, jrec, num_rec); double numRec = 0; int numFor = 0; String responseXML = null;/*from w w w . j a v a 2 s . com*/ BufferedReader br = null; try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { method.getResponseBody(); responseXML = convertStreamToString(method.getResponseBodyAsStream()); numRec = Double.parseDouble(responseXML.split("Results:")[1].split("-->")[0].replace(" ", "")); System.out.println("NUM REC=>" + numRec / 100); numFor = (int) Math.ceil(numRec / 100); System.out.println("NUM REC=>" + numFor); method.releaseConnection(); } } catch (IOException ex) { Logger.getLogger(aleph_portlet.class.getName()).log(Level.SEVERE, null, ex); } return numFor; }
From source file:net.sf.j2ep.ProxyFilter.java
/** * Will create the method and execute it. After this the method * is sent to a ResponseHandler that is returned. * /* w ww . j a v a 2s .c o m*/ * @param httpRequest Request we are receiving from the client * @param url The location we are proxying to * @return A ResponseHandler that can be used to write the response * @throws MethodNotAllowedException If the method specified by the request isn't handled * @throws IOException When there is a problem with the streams * @throws HttpException The httpclient can throw HttpExcetion when executing the method */ private ResponseHandler executeRequest(HttpServletRequest httpRequest, String url) throws MethodNotAllowedException, IOException, HttpException { RequestHandler requestHandler = RequestHandlerFactory.createRequestMethod(httpRequest.getMethod()); HttpMethod method = requestHandler.process(httpRequest, url); method.setFollowRedirects(false); /* * Why does method.validate() return true when the method has been * aborted? I mean, if validate returns true the API says that means * that the method is ready to be executed. TODO I don't like doing type * casting here, see above. */ if (!((HttpMethodBase) method).isAborted()) { httpClient.executeMethod(method); if (method.getStatusCode() == 405) { Header allow = method.getResponseHeader("allow"); String value = allow.getValue(); throw new MethodNotAllowedException("Status code 405 from server", AllowedMethodHandler.processAllowHeader(value)); } } return ResponseHandlerFactory.createResponseHandler(method); }
From source file:net.oauth.client.OAuthHttpClient.java
/** Send a message to the service provider and get the response. */ @Override/* w w w. j av a 2 s . c om*/ protected OAuthMessage invoke(OAuthMessage message) throws Exception { String form = OAuth.formEncode(message.getParameters()); HttpMethod method; if ("GET".equals(message.httpMethod)) { method = new GetMethod(message.URL); method.setQueryString(form); // method.addRequestHeader("Authorization", message // .getAuthorizationHeader(serviceProvider.userAuthorizationURL)); method.setFollowRedirects(false); } else { PostMethod post = new PostMethod(message.URL); post.setRequestEntity(new StringRequestEntity(form, OAuth.FORM_ENCODED, null)); method = post; } clientPool.getHttpClient(new URL(method.getURI().toString())).executeMethod(method); final OAuthMessage response = new HttpMethodResponse(method); int statusCode = method.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Map<String, Object> dump = response.getDump(); OAuthProblemException problem = new OAuthProblemException( (String) dump.get(OAuthProblemException.OAUTH_PROBLEM)); problem.getParameters().putAll(dump); throw problem; } return response; }
From source file:com.yahoo.flowetl.services.HttpService.java
/** * Calls the given http params and returns a result object. * /*from ww w . ja va2 s . co m*/ * @param params * * @return the http result */ public HttpResult call(HttpParams params) { Pair<HttpClient, HttpMethod> clientMet = generator.generate(params); HttpClient client = clientMet.getFirst(); HttpMethod toCall = clientMet.getSecond(); HttpResult out = new HttpResult(); out.statusCode = -1; out.sourceParams = params; InputStream is = null; try { if (logger.isEnabled(Level.INFO)) { logger.log(Level.INFO, "Running http method " + toCall + " with params " + params); } caller.execute(client, toCall, params.retries); is = toCall.getResponseBodyAsStream(); String responseBody = IOUtils.toString(is); int st = toCall.getStatusCode(); Header[] hv = toCall.getResponseHeaders(); // copy over out.statusCode = st; out.responseBody = responseBody; Map<String, String> headersIn = new TreeMap<String, String>(); if (hv != null) { for (Header h : hv) { headersIn.put(h.getName(), h.getValue()); } } out.headers = headersIn; } catch (HttpException e) { if (logger.isEnabled(Level.WARN)) { logger.log(Level.WARN, e, "Failed calling " + toCall); } } catch (IOException e) { if (logger.isEnabled(Level.WARN)) { logger.log(Level.WARN, e, "Failed calling " + toCall); } } finally { IOUtils.closeQuietly(is); toCall.releaseConnection(); } return out; }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a POST Message.//from w w w . j av a2 s . c om * * @param authpost * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws ProcessException on problems * @throws CookieException on problems */ protected String post(HttpMethod authpost, ContentProcessable cp) throws IOException, ProcessException, CookieException { showCookies(client); authpost.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); String out = ""; client.executeMethod(authpost); // Header locationHeader = authpost.getResponseHeader("location"); // if (locationHeader != null) { // authpost.setRequestHeader(locationHeader) ; // } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } LOG.debug("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); LOG.debug("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); authpost = redirect; } } out = authpost.getResponseBodyAsString(); out = cp.processReturningText(out, authpost); cp.validateReturningCookies(client.getState().getCookies(), authpost); authpost.releaseConnection(); LOG.debug(authpost.getURI() + " || " + "POST: " + authpost.getStatusLine().toString()); return out; }
From source file:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java
/** * Get Volum details from solr meta data instance. Here it adds '\' character before the ':'. * @param volId/*ww w . ja v a2 s . co m*/ * @return VolumeDetailsBean * @throws IOException */ public VolumeDetailsBean getVolumeDetails(String volId) throws IOException { String volumeId; if (volId.contains(":")) { volumeId = volId.substring(0, volId.indexOf(":")) + "\\" + volId.substring(volId.indexOf(":")); } else { volumeId = volId; } String volumeDetailsQueryUrl = PlayConfWrapper.solrMetaQueryUrl() + "id:" + URLEncoder.encode(volumeId, "UTF-8") + "&fl=title,author,htrc_genderMale,htrc_genderFemale,htrc_genderUnknown,htrc_pageCount,htrc_wordCount"; VolumeDetailsBean volDetails = new VolumeDetailsBean(); if (log.isDebugEnabled()) { log.debug(volumeDetailsQueryUrl); } HttpClient httpClient = new HttpClient(); HttpMethod method = new GetMethod(volumeDetailsQueryUrl); method.setFollowRedirects(true); try { httpClient.executeMethod(method); volDetails.setVolumeId(volId); if (method.getStatusCode() == 200 && !method.getResponseBodyAsString().contains("<warn>RESPONSE CODE: 400</warn>")) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); Document dom = documentBuilder.parse(method.getResponseBodyAsStream()); NodeList result = dom.getElementsByTagName("result"); NodeList arrays = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("arr"); NodeList integers = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("int"); NodeList longIntegers = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("long"); for (int i = 0; i < arrays.getLength(); i++) { org.w3c.dom.Element arr = (org.w3c.dom.Element) arrays.item(i); if (arr.hasAttribute("name") && arr.getAttribute("name").equals("title")) { NodeList strElements = arr.getElementsByTagName("str"); volDetails.setTitle((strElements.item(0)).getTextContent()); } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderMale")) { NodeList strElements = arr.getElementsByTagName("str"); String maleAuthor = ""; for (int j = 0; j < strElements.getLength(); j++) { org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j); if (j != strElements.getLength() - 1) { maleAuthor += str.getTextContent(); } else { maleAuthor += str.getTextContent(); } } volDetails.setMaleAuthor(maleAuthor); } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderFemale")) { NodeList strElements = arr.getElementsByTagName("str"); String femaleAuthor = ""; for (int j = 0; j < strElements.getLength(); j++) { org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j); if (j != strElements.getLength() - 1) { femaleAuthor += str.getTextContent(); } else { femaleAuthor += str.getTextContent(); } } volDetails.setFemaleAuthor(femaleAuthor); } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderUnknown")) { NodeList strElements = arr.getElementsByTagName("str"); String genderUnknownAuthor = ""; for (int j = 0; j < strElements.getLength(); j++) { org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j); if (j != strElements.getLength() - 1) { genderUnknownAuthor += str.getTextContent(); } else { genderUnknownAuthor += str.getTextContent(); } } volDetails.setGenderUnkownAuthor(genderUnknownAuthor); } } for (int i = 0; i < integers.getLength(); i++) { org.w3c.dom.Element integer = (org.w3c.dom.Element) integers.item(i); if (integer.hasAttribute("name") && integer.getAttribute("name").equals("htrc_pageCount")) { String pageCount = integer.getTextContent(); volDetails.setPageCount(pageCount); } } for (int i = 0; i < longIntegers.getLength(); i++) { org.w3c.dom.Element longInteger = (org.w3c.dom.Element) longIntegers.item(0); if (longInteger.hasAttribute("name") && longInteger.getAttribute("name").equals("htrc_wordCount")) { String wordCount = longInteger.getTextContent(); volDetails.setWordCount(wordCount); } } } else { volDetails.setTitle("Cannot retrieve volume details."); log.warn("Cannot retrieve details for volume id: " + volId + " Response body: \n" + method.getResponseBodyAsString()); } } catch (SAXParseException e) { log.error("Error while parsing volume details for volume: " + volId + " query url: " + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e); volDetails.setTitle("Cannot parse volume details."); } catch (ParserConfigurationException e) { log.error("Unrecoverable error while parsing volume details.", e); log.error("Error while parsing volume details for volume: " + volId + " query url: " + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e); throw new RuntimeException("Unrecoverable error while parsing volume details.", e); } catch (SAXException e) { log.error("Error while parsing volume details for volume: " + volId + " query url: " + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e); volDetails.setTitle("Cannot parse volume details."); } return volDetails; }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a GET Message.// www .j av a2s . c o m * * @param authgets * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws CookieException on problems * @throws ProcessException on problems */ public byte[] get(HttpMethod authgets) throws IOException, CookieException, ProcessException { showCookies(client); byte[] out = null; authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); // System.err.println(authgets.getParams().getParameter("http.protocol.content-charset")); client.executeMethod(authgets); LOG.debug(authgets.getURI()); LOG.debug("GET: " + authgets.getStatusLine().toString()); out = authgets.getResponseBody(); // release any connection resources used by the method authgets.releaseConnection(); int statuscode = authgets.getStatusCode(); if (statuscode == HttpStatus.SC_NOT_FOUND) { LOG.warn("Not Found: " + authgets.getQueryString()); throw new FileNotFoundException(authgets.getQueryString()); } return out; }