List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream
@Override public InputStream getResponseBodyAsStream() throws IOException
From source file:org.apache.jetspeed.portlets.sso.SSOTicketPortlet.java
private String requestTicket(String url, RenderRequest request, RenderResponse response) { // ...set up URL and HttpClient stuff String ticket = ""; HttpClient client = new HttpClient(); HttpMethodBase httpMethod = null; httpMethod = new PostMethod(); //String useragentProperty = request.getProperty("User-Agent"); httpMethod.addRequestHeader("User-Agent", "Firefox"); httpMethod.setPath(url);//ww w .j a v a 2s. com try { client.executeMethod(httpMethod); int responseCode = httpMethod.getStatusCode(); if (responseCode >= 300 && responseCode <= 399) { // redirection that could not be handled automatically!!! (probably from a POST) Header locationHeader = httpMethod.getResponseHeader("location"); String redirectLocation = locationHeader != null ? locationHeader.getValue() : null; if (redirectLocation != null) { // one more time (assume most params are already encoded & new URL is using GET protocol!) return requestTicket(redirectLocation, null, null); } else { // The response is a redirect, but did not provide the new location for the resource. throw new PortletException( "Redirection code: " + responseCode + ", but with no redirectionLocation set."); } } else if (responseCode == 200) { // String body = httpMethod.getResponseBodyAsString(); // Header [] head = httpMethod.getResponseHeaders(); TicketParamRewriter ticketWriter = new TicketParamRewriter(); String ticketName = (String) request.getPreferences().getValue(SSO_PREF_TICKET_NAME, null); if (ticketName != null) { ticketWriter.setTicketName(ticketName); Reader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); createParserAdaptor().parse(ticketWriter, reader); ticket = ticketWriter.getTicket(); } } } catch (Exception e) { logger.error("Unexpected error during request ticket.", e); } return ticket; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//from w w w . jav a 2s . co m * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HttpMethodBase httpMethod = null; HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time try { // May generate IllegalArgumentException if (method.equals(HTTPConstants.POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(HTTPConstants.GET)) { httpMethod = new GetMethod(urlStr); } else if (method.equals(HTTPConstants.PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HTTPConstants.HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(HTTPConstants.TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(HTTPConstants.OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(HTTPConstants.DELETE)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.DELETE; } }; } else if (method.equals(HTTPConstants.PATCH)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.PATCH; } }; } else { throw new IllegalArgumentException("Unexpected method: '" + method + "'"); } final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection HttpClient client = setupConnection(url, httpMethod, res); savedClient = client; // Handle the various methods if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData((PostMethod) httpMethod); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH) || method.equals(HTTPConstants.DELETE)) { String putBody = sendEntityData((EntityEnclosingMethod) httpMethod); res.setQueryString(putBody); } int statusCode = client.executeMethod(httpMethod); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = client.getHostConfiguration().getLocalAddress(); if (localAddr != null) { httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: InputStream instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD instream = new CountingInputStream(instream); try { Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) { InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting res.setResponseData( readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength())); } else { res.setResponseData( readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } } finally { JOrphanUtils.closeQuietly(instream); } } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); // in case sanitising fails } // record some sizes to allow HTTPSampleResult.getBytes() with different options if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); } res.setHeadersSize(calculateHeadersSize(httpMethod)); if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod can be null if method is unexpected if (httpMethod != null) { res.setRequestHeaders(getConnectionHeaders(httpMethod)); } errorResult(e, res); return res; } catch (IOException e) { res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod cannot be null here, otherwise // it would have been caught in the previous catch block res.setRequestHeaders(getConnectionHeaders(httpMethod)); errorResult(e, res); return res; } finally { savedClient = null; if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate./*from w w w. j a v a 2 s.c o m*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toExternalForm(); // Check if this is an entity-enclosing method boolean isPost = method.equals(POST) || method.equals(PUT); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); // Handles OAuth signing try { message = getOAuthMessage(url, method); urlStr = message.URL; if (isPost) { urlStr = message.URL; } else { if (useAuthHeader) urlStr = OAuth.addParameters(message.URL, nonOAuthParams); else urlStr = OAuth.addParameters(message.URL, message.getParameters()); } } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (OAuthException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (URISyntaxException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } log.debug("Start : sample " + urlStr); //$NON-NLS-1$ log.debug("method " + method); //$NON-NLS-1$ HttpMethodBase httpMethod = null; res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // May generate IllegalArgumentException if (method.equals(POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(DELETE)) { httpMethod = new DeleteMethod(urlStr); } else if (method.equals(GET)) { httpMethod = new GetMethod(urlStr); } else { log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$ httpMethod = new GetMethod(urlStr); } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(new URL(urlStr), httpMethod, res); // Handle POST and PUT if (isPost) { String postBody = sendPostData(httpMethod); res.setQueryString(postBody); } res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = client.executeMethod(httpMethod); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$ } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); //$NON-NLS-1$ httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.sling.commons.testing.integration.HttpTestBase.java
/** Return m's response body as a string, optionally limiting the length that we read * @param maxLength if 0, no limit//from ww w. j ava 2s . c o m */ public static String getResponseBodyAsStream(HttpMethodBase m, int maxLength) throws IOException { final InputStream is = m.getResponseBodyAsStream(); final StringBuilder content = new StringBuilder(); final String charset = m.getResponseCharSet(); final byte[] buffer = new byte[16384]; int n = 0; while ((n = is.read(buffer, 0, buffer.length)) > 0) { content.append(new String(buffer, 0, n, charset)); if (maxLength != 0 && content.length() > maxLength) { throw new IllegalArgumentException("Response body size is over maxLength (" + maxLength + ")"); } } return content.toString(); }
From source file:org.apache.synapse.mediators.json.SynapseJsonSender.java
private void processResponse(HttpMethodBase httpMethod, MessageContext msgContext) throws IOException { obtainHTTPHeaderInformation(httpMethod, msgContext); InputStream in = httpMethod.getResponseBodyAsStream(); Header contentEncoding = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { in = new GZIPInputStream(in); } else {// w ww.j a va2 s .c om throw new AxisFault( "HTTP :" + "unsupported content-encoding of '" + contentEncoding.getValue() + "' found"); } } if (in == null) { throw new AxisFault(Messages.getMessage("canNotBeNull", "InputStream")); } if (msgContext.getOperationContext() != null) { msgContext.getOperationContext().setProperty(MessageContext.TRANSPORT_IN, in); } }
From source file:org.appcelerator.transport.ProxyTransportServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getMethod(); String url = request.getParameter("url"); if (url == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return;/*from w ww. j a v a 2s .co m*/ } url = URLDecoder.decode(url, "UTF-8"); if (url.indexOf("://") == -1) { url = new String(Base64.decode(url)); } HttpClient client = new HttpClient(); HttpMethodBase methodBase = null; if (method.equalsIgnoreCase("POST")) { methodBase = new PostMethod(url); ByteArrayOutputStream out = new ByteArrayOutputStream(); Util.copy(request.getInputStream(), out); ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray()); ((PostMethod) methodBase).setRequestEntity(req); } else if (method.equalsIgnoreCase("GET")) { methodBase = new GetMethod(url); methodBase.setFollowRedirects(true); } else if (method.equalsIgnoreCase("PUT")) { methodBase = new PutMethod(url); ByteArrayOutputStream out = new ByteArrayOutputStream(); Util.copy(request.getInputStream(), out); ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray()); ((PutMethod) methodBase).setRequestEntity(req); } else if (method.equalsIgnoreCase("DELETE")) { methodBase = new DeleteMethod(url); } else if (method.equalsIgnoreCase("OPTIONS")) { methodBase = new OptionsMethod(url); } methodBase.setRequestHeader("User-Agent", request.getHeader("user-agent") + " (Appcelerator Proxy)"); if (LOG.isDebugEnabled()) { LOG.debug("Proxying url: " + url + ", method: " + method); } int status = client.executeMethod(methodBase); response.setStatus(status); response.setContentLength((int) methodBase.getResponseContentLength()); for (Header header : methodBase.getResponseHeaders()) { String name = header.getName(); if (name.equalsIgnoreCase("Set-Cookie") == false && name.equals("Transfer-Encoding") == false) { response.setHeader(name, header.getValue()); } } InputStream in = methodBase.getResponseBodyAsStream(); Util.copy(in, response.getOutputStream()); }
From source file:org.deegree.portal.owswatch.validator.AbstractValidator.java
/** * Validates the HttpMethodBase and checks if the execution was successful or not * * @param method/* www .j a v a 2 s. c o m*/ * the httpmethod after executing it * @return an instance of ValidatorResponse with the necessary information after validation */ protected ValidatorResponse validateXml(HttpMethodBase method) { String lastMessage = null; Status status = null; String contentType = method.getResponseHeader("Content-Type").getValue(); if (!contentType.contains("xml")) { status = Status.RESULT_STATE_UNEXPECTED_CONTENT; lastMessage = StringTools.concat(100, "Error: Response Content is ", contentType, " not xml"); return new ValidatorResponse(lastMessage, status); } String xml = null; try { InputStream stream = copyStream(method.getResponseBodyAsStream()); stream.reset(); xml = parseStream(stream); } catch (IOException e) { status = Status.RESULT_STATE_BAD_RESPONSE; lastMessage = status.getStatusMessage(); return new ValidatorResponse(lastMessage, status); } if (xml.length() == 0) { status = Status.RESULT_STATE_BAD_RESPONSE; lastMessage = "Error: XML Response is empty"; return new ValidatorResponse(lastMessage, status); } if (xml.contains("ServiceException")) { return validateXmlServiceException(method); } // If its an xml, and there's no service exception, then don't really parse the xml, // we assume that its well formed, since there might be huge xmls, which would take time to be parsed status = Status.RESULT_STATE_AVAILABLE; lastMessage = status.getStatusMessage(); return new ValidatorResponse(lastMessage, status); }
From source file:org.deegree.portal.owswatch.validator.AbstractValidator.java
/** * This method is called To read the ServiceExceptionReport from the xml file * * @param method/*from w w w. ja va2s. com*/ * the httpmethod after executing it * @return an instance of ValidatorResponse with the necessary information after validation */ protected ValidatorResponse validateXmlServiceException(HttpMethodBase method) { Document doc = null; String lastMessage = null; Status status = null; try { InputStream stream = method.getResponseBodyAsStream(); stream.reset(); doc = instantiateParser().parse(stream); } catch (Exception e) { status = Status.RESULT_STATE_INVALID_XML; lastMessage = "Error: MalFormed XML Response"; return new ValidatorResponse(lastMessage, status); } try { status = Status.RESULT_STATE_SERVICE_UNAVAILABLE; lastMessage = XMLTools.getNodeAsString(doc.getDocumentElement(), "./ServiceException", null, "Service Unavailable. Unknown error"); return new ValidatorResponse(lastMessage, status); } catch (XMLParsingException e) { status = Status.RESULT_STATE_SERVICE_UNAVAILABLE; lastMessage = status.getStatusMessage(); return new ValidatorResponse(lastMessage, status); } }
From source file:org.deegree.portal.owswatch.validator.CSWGetRecordsValidator.java
@Override public ValidatorResponse validateAnswer(HttpMethodBase method, int statusCode) { String contentType = method.getResponseHeader("Content-Type").getValue(); String lastMessage = null;/*w ww . j a va 2 s .c o m*/ Status status = null; if (!contentType.contains("xml")) { status = Status.RESULT_STATE_UNEXPECTED_CONTENT; lastMessage = StringTools.concat(100, "Error: Response Content is ", contentType, " not xml"); return new ValidatorResponse(lastMessage, status); } String xml = null; try { InputStream stream = method.getResponseBodyAsStream(); stream.reset(); xml = parseStream(stream); } catch (IOException e) { status = Status.RESULT_STATE_BAD_RESPONSE; lastMessage = status.getStatusMessage(); return new ValidatorResponse(lastMessage, status); } if (xml.length() == 0) { status = Status.RESULT_STATE_BAD_RESPONSE; lastMessage = "Error: XML Response is empty"; return new ValidatorResponse(lastMessage, status); } if (xml.contains("ExceptionReport")) { validateXmlServiceException(method); return new ValidatorResponse(lastMessage, status); } // If its an xml, and there's no service exception, then don't really parse the xml, // we assume that its well formed, since there might be huge xmls, which would take time to be parsed status = Status.RESULT_STATE_AVAILABLE; lastMessage = status.getStatusMessage(); return new ValidatorResponse(lastMessage, status); }
From source file:org.deegree.portal.owswatch.validator.CSWGetRecordsValidator.java
@Override protected ValidatorResponse validateXmlServiceException(HttpMethodBase method) { Document doc = null;//from w w w. j av a 2 s.co m String lastMessage = null; Status status = null; try { InputStream stream = method.getResponseBodyAsStream(); stream.reset(); doc = instantiateParser().parse(stream); } catch (Exception e) { status = Status.RESULT_STATE_INVALID_XML; lastMessage = "Error: MalFormed XML Response"; return new ValidatorResponse(lastMessage, status); } try { NamespaceContext cnxt = CommonNamespaces.getNamespaceContext(); URI owsns = CommonNamespaces.OWSNS; String prefix = doc.lookupPrefix(owsns.toASCIIString()); StringBuilder builder = new StringBuilder(100); builder.append("./"); if (prefix != null && prefix.length() > 0) { builder.append(prefix).append(":"); cnxt.addNamespace(prefix, owsns); } builder.append("Exception"); status = Status.RESULT_STATE_SERVICE_UNAVAILABLE; lastMessage = XMLTools.getNodeAsString(doc.getDocumentElement(), builder.toString(), cnxt, "Service Unavailable. Unknown error"); return new ValidatorResponse(lastMessage, status); } catch (XMLParsingException e) { lastMessage = "Service Unavailable"; status = Status.RESULT_STATE_SERVICE_UNAVAILABLE; return new ValidatorResponse(lastMessage, status); } }