List of usage examples for org.apache.commons.httpclient HttpMethodBase setPath
@Override public void setPath(String path)
From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java
/** * Add the ticket parameter to the request * @param method The method to expand// ww w.j a va2 s. com * @param ticket The ticket to use */ protected void addTicketParameter(HttpMethodBase method, String ticket) { method.setPath(method.getPath() + "?" + DEFAULT_TICKET_NAME + "=" + ticket); }
From source file:jeeves.utils.XmlRequest.java
private Element doExecute(HttpMethodBase httpMethod) throws IOException, BadXmlResponseEx { config.setHost(host, port, Protocol.getProtocol(protocol)); if (useProxy) config.setProxy(proxyHost, proxyPort); byte[] data = null; try {//from w ww . j av a 2s . co m client.executeMethod(httpMethod); data = httpMethod.getResponseBody(); // HttpClient is unable to automatically handle redirects of entity // enclosing methods such as POST and PUT. // Get the location header and run the request against it. String redirectLocation; Header locationHeader = httpMethod.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); httpMethod.setPath(redirectLocation); client.executeMethod(httpMethod); data = httpMethod.getResponseBody(); } return Xml.loadStream(new ByteArrayInputStream(data)); } catch (JDOMException e) { throw new BadXmlResponseEx(new String(data, "UTF8")); } finally { httpMethod.releaseConnection(); sentData = getSentData(httpMethod); receivedData = getReceivedData(httpMethod, data); } }
From source file:jeeves.utils.XmlRequest.java
private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException { HttpMethodBase httpMethod; if (method == Method.GET) { httpMethod = new GetMethod(); if (query != null && !query.equals("")) httpMethod.setQueryString(query); else if (alSimpleParams.size() != 0) httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()])); httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml"); httpMethod.setFollowRedirects(true); } else {/*from w w w . j av a 2 s .c o m*/ PostMethod post = new PostMethod(); if (!useSOAP) { postData = (postParams == null) ? "" : Xml.getString(new Document(postParams)); post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8")); } else { postData = Xml.getString(new Document(soapEmbed(postParams))); post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8")); } httpMethod = post; } httpMethod.setPath(address); httpMethod.setDoAuthentication(useAuthent()); return httpMethod; }
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
/** * Method used to copy all the common properties * * @param msgContext - The messageContext of the request message * @param url - The target URL * @param httpMethod - The http method used to send the request * @param httpClient - The httpclient used to send the request * @param soapActionString - The soap action atring of the request message * @return MessageFormatter - The messageFormatter for the relavent request message * @throws AxisFault - Thrown in case an exception occurs */// w w w .jav a 2s .c o m protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url, HttpMethodBase httpMethod, HttpClient httpClient, String soapActionString) throws AxisFault { if (isAuthenticationEnabled(msgContext)) { httpMethod.setDoAuthentication(true); } MessageFormatter messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext); url = messageFormatter.getTargetAddress(msgContext, format, url); httpMethod.setPath(url.getPath()); httpMethod.setQueryString(url.getQuery()); httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, soapActionString)); httpMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost()); if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) { // setting the cookie in the out path Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING); if (cookieString != null) { StringBuffer buffer = new StringBuffer(); buffer.append(cookieString); httpMethod.setRequestHeader(HTTPConstants.HEADER_COOKIE, buffer.toString()); } } if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) { httpClient.getParams().setVersion(HttpVersion.HTTP_1_0); } return messageFormatter; }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Method used to copy all the common properties * //from w w w . j av a 2 s . co m * @param msgContext * - The messageContext of the request message * @param url * - The target URL * @param httpMethod * - The http method used to send the request * @param httpClient * - The httpclient used to send the request * @param soapActionString * - The soap action atring of the request message * @return MessageFormatter - The messageFormatter for the relavent request * message * @throws AxisFault * - Thrown in case an exception occurs */ protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url, HttpMethodBase httpMethod, HttpClient httpClient, String soapActionString) throws AxisFault { if (isAuthenticationEnabled(msgContext)) { httpMethod.setDoAuthentication(true); } MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext); url = messageFormatter.getTargetAddress(msgContext, format, url); httpMethod.setPath(url.getPath()); httpMethod.setQueryString(url.getQuery()); httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, soapActionString)); httpMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost()); if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) { // setting the cookie in the out path Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING); if (cookieString != null) { StringBuffer buffer = new StringBuffer(); buffer.append(cookieString); httpMethod.setRequestHeader(HTTPConstants.HEADER_COOKIE, buffer.toString()); } } if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) { httpClient.getParams().setVersion(HttpVersion.HTTP_1_0); } return messageFormatter; }
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); try {//w ww. ja va 2 s . c o m 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.fao.geonet.csw.common.requests.CatalogRequest.java
private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException { HttpMethodBase httpMethod; if (method == Method.GET) { alGetParams = new ArrayList<NameValuePair>(); if (alSetupGetParams.size() != 0) { alGetParams.addAll(alSetupGetParams); }//from www.ja v a 2s . c o m setupGetParams(); httpMethod = new GetMethod(); httpMethod.setPath(path); httpMethod.setQueryString(alGetParams.toArray(new NameValuePair[1])); System.out.println("GET params:" + httpMethod.getQueryString()); if (useSOAP) httpMethod.addRequestHeader("Accept", "application/soap+xml"); } else { Element params = getPostParams(); PostMethod post = new PostMethod(); if (!useSOAP) { postData = Xml.getString(new Document(params)); post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8")); } else { postData = Xml.getString(new Document(soapEmbed(params))); post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8")); } System.out.println("POST params:" + Xml.getString(params)); httpMethod = post; httpMethod.setPath(path); } // httpMethod.setFollowRedirects(true); if (useAuthent) { Credentials cred = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); client.getState().setCredentials(scope, cred); httpMethod.setDoAuthentication(true); } return httpMethod; }
From source file:org.fao.oaipmh.requests.Transport.java
private HttpMethodBase setupHttpMethod() { HttpMethodBase httpMethod; if (method == Method.GET) { httpMethod = new GetMethod(); httpMethod.setQueryString(alParams.toArray(new NameValuePair[1])); } else {//from ww w . j a v a2 s . c om PostMethod pm = new PostMethod(); pm.setRequestBody(alParams.toArray(new NameValuePair[1])); httpMethod = pm; } httpMethod.setPath(address); httpMethod.setDoAuthentication(useAuthent()); return httpMethod; }
From source file:org.openlaszlo.data.HTTPDataSource.java
/** * @param since last modified time to use * @param req//from w w w . j a va 2 s . co m * @param url if null, ignored * @param redirCount number of redirs we've done */ public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl, int redirCount, int timeout) throws IOException, HttpException, DataSourceException, MalformedURLException { HttpMethodBase request = null; HostConfiguration hcfg = new HostConfiguration(); /* [todo hqm 2006-02-01] Anyone know why this code was here? It is setting the mime type to something which just confuses the DHTML parser. if (res != null) { res.setContentType("application/x-www-form-urlencoded;charset=UTF-8"); } */ try { // TODO: [2002-01-09 bloch] cope with cache-control // response headers (no-store, no-cache, must-revalidate, // proxy-revalidate). if (surl == null) { surl = getURL(req); } if (surl == null || surl.equals("")) { throw new MalformedURLException( /* (non-Javadoc) * @i18n.test * @org-mes="url is empty or null" */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-312")); } String reqType = ""; String headers = ""; if (req != null) { reqType = req.getParameter("reqtype"); headers = req.getParameter("headers"); } boolean isPost = false; mLogger.debug("reqtype = " + reqType); if (reqType != null && reqType.equals("POST")) { request = new LZPostMethod(); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); isPost = true; mLogger.debug("setting POST req method"); } else if (reqType != null && reqType.equals("PUT")) { request = new LZPutMethod(); // todo [hqm 2007] treat PUT like POST? isPost = true; mLogger.debug("setting PUT req method"); } else if (reqType != null && reqType.equals("DELETE")) { request = new LZDeleteMethod(); mLogger.debug("setting DELETE req method"); } else { mLogger.debug("setting GET (default) req method"); request = new LZGetMethod(); } request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0); // Proxy the request headers if (req != null) { LZHttpUtils.proxyRequestHeaders(req, request); } // Set headers from query string if (headers != null && headers.length() > 0) { StringTokenizer st = new StringTokenizer(headers, "\n"); while (st.hasMoreTokens()) { String h = st.nextToken(); int i = h.indexOf(":"); if (i > -1) { String n = h.substring(0, i); String v = h.substring(i + 2, h.length()); request.setRequestHeader(n, v); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="setting header " + p[0] + "=" + p[1] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-359", new Object[] { n, v })); } } } mLogger.debug("Parsing url"); URI uri = LZHttpUtils.newURI(surl); try { hcfg.setHost(uri); } catch (Exception e) { throw new MalformedURLException( /* (non-Javadoc) * @i18n.test * @org-mes="can't form uri from " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376", new Object[] { surl })); } // This gets us the url-encoded (escaped) path and query string String path = uri.getEscapedPath(); String query = uri.getEscapedQuery(); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="encoded path: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389", new Object[] { path })); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="encoded query: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397", new Object[] { query })); // This call takes a decoded (unescaped) path request.setPath(path); boolean hasQuery = (query != null && query.length() > 0); String rawcontent = null; // Newer rawpost protocol puts lzpostbody as a separate // top level query arg in the request. rawcontent = req.getParameter("lzpostbody"); if (isPost) { // Older rawpost protocol put the "lzpostbody" arg // embedded in the "url" args's query args if (rawcontent == null && hasQuery) { rawcontent = findQueryArg("lzpostbody", query); } if (rawcontent != null) { // Get the unescaped query string ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent)); } else if (hasQuery) { StringTokenizer st = new StringTokenizer(query, "&"); while (st.hasMoreTokens()) { String it = st.nextToken(); int i = it.indexOf("="); if (i > 0) { String n = it.substring(0, i); String v = it.substring(i + 1, it.length()); // POST encodes values during request ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8")); } else { mLogger.warn( /* (non-Javadoc) * @i18n.test * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-429", new Object[] { it })); } } } } else { // This call takes an encoded (escaped) query string request.setQueryString(query); } // Put in the If-Modified-Since headers if (since != -1) { String lms = LZHttpUtils.getDateString(since); request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="proxying lms: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450", new Object[] { lms })); } mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="setting up http client" */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460")); HttpClient htc = null; if (mConnectionMgr != null) { htc = new HttpClient(mConnectionMgr); } else { htc = new HttpClient(); } htc.setHostConfiguration(hcfg); // This is the data timeout mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="timeout set to " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478", new Object[] { timeout })); htc.getParams().setSoTimeout(timeout); // Set connection timeout the same htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout); // Set timeout for getting a connection htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout); // TODO: [2003-03-05 bloch] this should be more configurable (per app?) if (!isPost) { request.setFollowRedirects(mFollowRedirects > 0); } long t1 = System.currentTimeMillis(); mLogger.debug("starting remote request"); int rc = htc.executeMethod(hcfg, request); String status = HttpStatus.getStatusText(rc); if (status == null) { status = "" + rc; } mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="remote response status: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504", new Object[] { status })); HttpData data = null; if (isRedirect(rc) && mFollowRedirects > redirCount) { String loc = request.getResponseHeader("Location").toString(); String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length()); mLogger.info( /* (non-Javadoc) * @i18n.test * @org-mes="Following URL from redirect: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517", new Object[] { hostURI })); long t2 = System.currentTimeMillis(); if (timeout > 0) { timeout -= (t2 - t1); if (timeout < 0) { throw new InterruptedIOException( /* (non-Javadoc) * @i18n.test * @org-mes=p[0] + " timed out after redirecting to " + p[1] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-529", new Object[] { surl, loc })); } } data = getDataOnce(req, res, since, hostURI, redirCount++, timeout); } else { data = new HttpData(request, rc); } if (req != null && res != null) { // proxy response headers LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure()); } return data; } catch (ConnectTimeoutException ce) { // Transduce to an InterrupedIOException, since lps takes these to be timeouts. if (request != null) { request.releaseConnection(); } throw new InterruptedIOException( /* (non-Javadoc) * @i18n.test * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs." */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557", new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout })); } catch (HttpRecoverableException hre) { if (request != null) { request.releaseConnection(); } throw hre; } catch (HttpException e) { if (request != null) { request.releaseConnection(); } throw e; } catch (IOException ie) { if (request != null) { request.releaseConnection(); } throw ie; } catch (RuntimeException e) { if (request != null) { request.releaseConnection(); } throw e; } }
From source file:smartrics.rest.fitnesse.fixture.support.http.URIBuilder.java
@SuppressWarnings("deprecation") public void setURI(org.apache.commons.httpclient.HttpMethodBase m, URI uri) throws URIException { HostConfiguration conf = m.getHostConfiguration(); if (uri.isAbsoluteURI()) { conf.setHost(new HttpHost(uri)); m.setHostConfiguration(conf);/* w ww . ja v a2s . c o m*/ } m.setPath(uri.getPath() != null ? uri.getEscapedPath() : "/"); m.setQueryString(uri.getQuery()); }