List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader
@Override public void addRequestHeader(String headerName, String headerValue)
From source file:org.apache.solr.servlet.NoCacheHeaderTest.java
protected void doLastModified(String method) throws Exception { // We do a first request to get the last modified // This must result in a 200 OK response HttpMethodBase get = getSelectMethod(method); getClient().executeMethod(get);//ww w .j a va2 s . c om checkResponseBody(method, get); assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode()); Header head = get.getResponseHeader("Last-Modified"); assertNull("We got a Last-Modified header", head); // If-Modified-Since tests get = getSelectMethod(method); get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date())); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here", 200, get.getStatusCode()); get = getSelectMethod(method); get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(System.currentTimeMillis() - 10000))); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here", 200, get.getStatusCode()); // If-Unmodified-Since tests get = getSelectMethod(method); get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(System.currentTimeMillis() - 10000))); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 with If-Unmodified-Since header. We should never get a 304 here", 200, get.getStatusCode()); get = getSelectMethod(method); get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date())); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 with If-Unmodified-Since header. We should never get a 304 here", 200, get.getStatusCode()); }
From source file:org.apache.solr.servlet.NoCacheHeaderTest.java
protected void doETag(String method) throws Exception { HttpMethodBase get = getSelectMethod(method); getClient().executeMethod(get);/*from w ww. j av a 2s . c o m*/ checkResponseBody(method, get); assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode()); Header head = get.getResponseHeader("ETag"); assertNull("We got an ETag in the response", head); // If-None-Match tests // we set a non matching ETag get = getSelectMethod(method); get.addRequestHeader("If-None-Match", "\"xyz123456\""); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-None-Match: Got no response code 200 in response to non matching ETag", 200, get.getStatusCode()); // we now set the special star ETag get = getSelectMethod(method); get.addRequestHeader("If-None-Match", "*"); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-None-Match: Got no response 200 for star ETag", 200, get.getStatusCode()); // If-Match tests // we set a non matching ETag get = getSelectMethod(method); get.addRequestHeader("If-Match", "\"xyz123456\""); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-Match: Got no response code 200 in response to non matching ETag", 200, get.getStatusCode()); // now we set the special star ETag get = getSelectMethod(method); get.addRequestHeader("If-Match", "*"); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-Match: Got no response 200 to star ETag", 200, get.getStatusCode()); }
From source file:org.craftercms.cstudio.loadtesting.actions.BaseAction.java
public int runAction(HttpClient httpClient, HttpMethodBase method, String username) throws Exception { HttpClientParams params = new HttpClientParams(); params.setSoTimeout(0);//from w ww . j a va 2 s .co m httpClient.setParams(params); if (username != null) { method.addRequestHeader("cookie", "username=" + username); } return httpClient.executeMethod(method); }
From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java
/** * Extracts info from message context./* w w w . j a v a 2 s . com*/ * * @param method * Post method * @param httpClient * The client used for posting * @param msgContext * the message context * @param tmpURL * the url to post to. * @throws Exception */ protected void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request // if (msgContext.getTimeout() != 0) { // /* ISSUE: these are not the same, but MessageContext has only one // definition of timeout */ // // SO_TIMEOUT -- timeout for blocking reads // httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout()); // // timeout for initial connection // httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout()); // } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$ if (action == null) { action = ""; //$NON-NLS-1$ } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$ method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$ String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); //$NON-NLS-1$ if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } httpClient.getState().setCredentials(AuthScope.ANY, proxyCred); } // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. //Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) { continue; } method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { Map.Entry me = (Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { String val = me.getValue().toString(); if (null != val) { httpChunkStream = JavaUtils.isTrue(val); } } else { // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes) if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) { method.setRequestHeader(key, value); } else { method.addRequestHeader(key, value); } } } } }
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); }//ww w . ja v a 2 s. com 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.geotools.data.wfs.protocol.http.DefaultHTTPProtocol.java
/** * //from ww w . j av a 2s.c o m * @param httpRequest * either a {@link HttpMethod} or {@link PostMethod} set up with the request to be * sent * @return * @throws IOException */ private HTTPResponse issueRequest(final HttpMethodBase httpRequest) throws IOException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Executing HTTP request: " + httpRequest.getURI()); } if (client == null) { client = new HttpClient(); client.getParams().setParameter("http.useragent", "GeoTools " + GeoTools.getVersion() + " WFS DataStore"); } if (timeoutMillis > 0) { client.getParams().setSoTimeout(timeoutMillis); } // TODO: remove this System.err.println("Executing HTTP request: " + httpRequest); if (isTryGzip()) { LOGGER.finest("Adding 'Accept-Encoding=gzip' header to request"); httpRequest.addRequestHeader("Accept-Encoding", "gzip"); } int statusCode; try { statusCode = client.executeMethod(httpRequest); } catch (IOException e) { httpRequest.releaseConnection(); throw e; } if (statusCode != HttpStatus.SC_OK) { httpRequest.releaseConnection(); String statusText = HttpStatus.getStatusText(statusCode); throw new IOException("Request failed with status code " + statusCode + "(" + statusText + "): " + httpRequest.getURI()); } HTTPResponse httpResponse = new HTTPClientResponse(httpRequest); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Got " + httpResponse); } return httpResponse; }
From source file:org.httpobjects.proxy.Proxy.java
protected Response proxyRequest(Request req, final HttpMethodBase method) { method.setFollowRedirects(false);/*from w w w . j a v a 2s . c om*/ String path = req.path().valueFor("path"); if (!path.startsWith("/")) path = "/" + path; String query = getQuery(req); if (query == null) { query = ""; } else { query = "?" + query; } String url = base + path + query; log.debug("doing a " + method.getClass().getSimpleName() + " for " + url); // log.debug("Content type is " + req.representation().contentType()); try { method.setURI(new URI(processUrl(url), true)); } catch (URIException e1) { throw new RuntimeException("Error with uri: " + url, e1); } addRequestHeaders(req, method); if (req.representation().contentType() != null) { method.addRequestHeader("Content-Type", req.representation().contentType()); } for (Header next : method.getRequestHeaders()) { log.debug("Sending header: " + next); } HttpClient client = createHttpClient(); return executeMethod(client, method, req); }
From source file:org.httpobjects.proxy.Proxy.java
protected void addRequestHeaders(Request req, final HttpMethodBase method) { for (HeaderField next : req.header().fields()) { method.addRequestHeader(next.name(), next.value()); }/* w ww .j a va 2 s .c o m*/ }
From source file:org.jboss.soa.esb.actions.http.HttpAction.java
public Message process(final Message msg) throws ActionProcessingException { try {/*from ww w . j a va2 s. c o m*/ final HttpClient client = new HttpClient(); final Properties props = msg.getProperties(); final String[] names = props.getNames(); if (METHOD_DELETE.equals(method)) { final HttpMethodBase req = new DeleteMethod(uri); for (int i = 0; i < names.length; i++) { final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]); if (headerMatcher.find()) req.addRequestHeader(headerMatcher.group(1), (String) props.getProperty(headerMatcher.group())); } client.executeMethod(req); final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); proxy.setPayload(msg, req.getResponseBodyAsString()); } else if (METHOD_GET.equals(method)) { final HttpMethodBase req = new GetMethod(uri); final List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (int i = 0; i < names.length; i++) { final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]); if (headerMatcher.find()) { req.addRequestHeader(headerMatcher.group(1), (String) props.getProperty(headerMatcher.group())); continue; } final Matcher paramMatcher = PATTERN_PARAM.matcher(names[i]); if (paramMatcher.find()) paramList.add(new NameValuePair(paramMatcher.group(1), (String) props.getProperty(paramMatcher.group()))); } req.setQueryString(paramList.toArray(new NameValuePair[] {})); client.executeMethod(req); final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); proxy.setPayload(msg, req.getResponseBodyAsString()); } else if (METHOD_POST.equals(method)) { final PostMethod req = new PostMethod(uri); for (int i = 0; i < names.length; i++) { final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]); if (headerMatcher.find()) { req.addRequestHeader(headerMatcher.group(1), (String) props.getProperty(headerMatcher.group())); continue; } final Matcher paramMatcher = PATTERN_PARAM.matcher(names[i]); if (paramMatcher.find()) req.addParameter(new NameValuePair(paramMatcher.group(1), (String) props.getProperty(paramMatcher.group()))); } req.setRequestEntity(new StringRequestEntity((String) proxy.getPayload(msg), null, null)); client.executeMethod(req); final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); proxy.setPayload(msg, req.getResponseBodyAsString()); } else if (METHOD_PUT.equals(method)) { final EntityEnclosingMethod req = new PutMethod(uri); for (int i = 0; i < names.length; i++) { final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]); if (headerMatcher.find()) req.addRequestHeader(headerMatcher.group(1), (String) props.getProperty(headerMatcher.group())); } req.setRequestEntity(new StringRequestEntity((String) proxy.getPayload(msg), null, null)); client.executeMethod(req); final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); proxy.setPayload(msg, req.getResponseBodyAsString()); } } catch (final Exception e) { throw new ActionProcessingException("Can't process message", e); } return msg; }
From source file:org.openlaszlo.utils.LZHttpUtils.java
/** Add request headers into method. * * @param req http servlet request object * @param method method to insert request headers into *//*from w w w .ja v a 2 s.co m*/ static public void proxyRequestHeaders(HttpServletRequest req, HttpMethodBase method) { mLogger.debug("proxyRequestHeaders"); // Copy all headers, if the servlet container allows, otherwise just // copy the cookie header and log a message. Enumeration<?> headerNames = req.getHeaderNames(); if (headerNames != null) { // Connection header tokens not to forward Enumeration<?> connEnum = req.getHeaders(CONNECTION); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); if (allowForward(key, connEnum)) { String val = (String) req.getHeader(key); method.addRequestHeader(key, val); mLogger.debug(" " + key + "=" + val); } } } else { mLogger.warn( /* (non-Javadoc) * @i18n.test * @org-mes="Can't get header names to proxy request headers" */ org.openlaszlo.i18n.LaszloMessages.getMessage(LZHttpUtils.class.getName(), "051018-237")); Enumeration<?> cookieEnum = req.getHeaders(COOKIE); if (cookieEnum != null) { while (cookieEnum.hasMoreElements()) { String val = (String) cookieEnum.nextElement(); method.addRequestHeader(COOKIE, val); mLogger.debug(" Cookie=" + val); } } Enumeration<?> authEnum = req.getHeaders(AUTHORIZATION); if (authEnum != null) { while (authEnum.hasMoreElements()) { String val = (String) authEnum.nextElement(); method.addRequestHeader(AUTHORIZATION, val); mLogger.debug(" Authorization=" + val); } } } }