List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader
@Override public void addRequestHeader(String headerName, String headerValue)
From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext//w w w.j a v a 2 s . co m * the messsage context * * @throws AxisFault */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke")); try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); log.info("POST message created with target [" + targetURL.toString() + "]"); TransactionContext transactionContext = TransactionContextFactory.get(); transactionContext .addDebugInformation("POST message created with target [" + targetURL.toString() + "]"); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY); if (cred instanceof UsernamePasswordCredentials) { log.trace("POST message created on client with credentials [" + ((UsernamePasswordCredentials) cred).getUserName() + ", " + ((UsernamePasswordCredentials) cred).getPassword() + "]."); } MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); log.info("HTTPCommonsSender - zipping request."); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); log.info("HTTPCommonsSender - not zipping request"); } ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); log.info("GET message created with target [" + targetURL.toString() + "]"); addContextInfo(method, httpClient, msgContext, targetURL); } if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) log.info("HTTPCommonsSender - accepting GZIP"); else log.info("HTTPCommonsSender - NOT accepting GZIP"); String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) method.getParams().setVersion(HttpVersion.HTTP_1_0); // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } // add HTTP header fields that the application thinks are "interesting" // the expectation is that these would be non-standard HTTP headers, // by convention starting with "xxx-" VistaRealmPrincipal principal = VistaRealmSecurityContext.get(); if (principal != null) { log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available."); String duz = principal.getDuz(); if (duz != null && duz.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz); String fullname = principal.getFullName(); if (fullname != null && fullname.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname); String sitename = principal.getSiteName(); if (sitename != null && sitename.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename); String sitenumber = principal.getSiteNumber(); if (sitenumber != null && sitenumber.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber); String ssn = principal.getSsn(); if (ssn != null && ssn.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn); String securityToken = principal.getSecurityToken(); if (securityToken != null && securityToken.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId, securityToken); String cacheLocationId = principal.getCacheLocationId(); if (cacheLocationId != null && cacheLocationId.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId, cacheLocationId); String userDivision = principal.getUserDivision(); if (userDivision != null && userDivision.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision); } else log.debug("SecurityContext credentials are NOT available."); method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store"); method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache"); try { log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "]"); } catch (IllegalStateException isX) { } // send the HTTP request and wait for a response int returnCode = httpClient.executeMethod(hostConfiguration, method, null); TransactionContext transactionContext = TransactionContextFactory.get(); // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source //transactionContext.setResponseCode (String.valueOf (returnCode)); // How many bytes received? transactionContext.setDataSourceBytesReceived(method.getBytesReceived()); // How long did it take to start getting a response coming back? Long timeSent = method.getTimeRequestSent(); Long timeReceived = method.getTimeFirstByteReceived(); if (timeSent != null && timeReceived != null) { long timeTook = timeReceived.longValue() - timeSent.longValue(); transactionContext.setTimeToFirstByte(new Long(timeTook)); } // Looks like it wasn't found in cache - is there a place to set this to true if it was? transactionContext.setItemCached(Boolean.FALSE); // extract the basic HTTP header fields for content type, location and length String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); try { log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "] failed - '" + statusMessage + "'."); } catch (IllegalStateException isX) { } AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to // pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "=" + (contentEncoding == null ? "null" : contentEncoding.getValue())); if (contentEncoding != null) { if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); log.debug("HTTPCommonsSender - receiving gzipped stream."); } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) { releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream( releaseConnectionOnCloseStream); log.debug("HTTPCommonsSender - receiving 'deflated' stream."); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); log.warn(fault.getMessage()); throw fault; } } try { log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "] succeeded, parsing response."); } catch (IllegalStateException isX) { } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP // message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isTraceEnabled()) { if (null == contentLength) log.trace("\n" + Messages.getMessage("no00", "Content-Length")); log.trace("\n" + Messages.getMessage("xmlRecd00")); log.trace("-----------------------------------------------"); log.trace(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }
From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java
/** * Extracts info from message context./* w w w . j av a 2s . c o m*/ * * @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 * @deprecated */ private 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.setTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.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$ 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 cred = new UsernamePasswordCredentials(userID, passwd); httpClient.getState().setCredentials(null, null, cred); // Change #2 // // Comment out the lines below since they force all authentication // to be Basic. This is a problem if the web service you're invoking // is expecting Digest. // The following 3 lines should NOT be required. But Our SimpleAxisServer fails // during all-tests if this is missing. // StringBuffer tmpBuf = new StringBuffer(); // tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd); // method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes())); } // 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(); method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { java.util.Map.Entry me = (java.util.Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); method.addRequestHeader(key, value); } } }
From source file:org.anhonesteffort.flock.webdav.DavClient.java
public int execute(HttpMethodBase method) throws IOException { method.addRequestHeader("Connection", "Keep-Alive"); method.addRequestHeader("Keep-Alive", "timeout=" + KEEP_ALIVE_TIMEOUT_SECONDS); return client.executeMethod(hostConfiguration, method); }
From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java
/** * Executes the current request by using HttpClient methods and returns the response. * * @return - Response from the Ambari server/Agent server. * @throws IOException//from w w w . ja v a 2s .c o m */ private WebResponse executeRequest() throws IOException { HttpMethodBase methodBase = null; String httpMethod; httpMethod = getHttpMethod(); if (httpMethod.equals("GET")) { methodBase = getGetMethod(); } else if (httpMethod.equals("POST")) { methodBase = getPostMethod(); } else if (httpMethod.equals("PUT")) { methodBase = getPutMethod(); } else if (httpMethod.equals("DELETE")) { methodBase = getDeleteMethod(); } else { new RuntimeException(String.format("Unsupported HTTP method: %s", httpMethod)); } WebResponse response = new WebResponse(); HttpClient httpClient = new HttpClient(); Map<String, String> headers = getHeaders(); for (Map.Entry<String, String> header : headers.entrySet()) { methodBase.addRequestHeader(header.getKey(), header.getValue()); } methodBase.setQueryString(getQueryString()); try { int statusCode = httpClient.executeMethod(methodBase); response.setStatusCode(statusCode); response.setContent(methodBase.getResponseBodyAsString()); } finally { methodBase.releaseConnection(); } return response; }
From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java
/** * Set the auth key header of the method to the token ID supplied * @param method method/* www. j a v a2 s .c o m*/ * @param accessToken access token * @throws SwiftInternalStateException if the client is not yet authenticated */ private void setAuthToken(HttpMethodBase method, AccessToken accessToken) throws SwiftInternalStateException { checkNotNull(accessToken, "Not authenticated"); method.addRequestHeader(HEADER_AUTH_KEY, accessToken.getId()); }
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);// w w w. j a v a2 s . c o m 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 ww . j a v a 2s . com*/ * <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.kylin.jdbc.KylinClient.java
private void addHttpHeaders(HttpMethodBase method) { method.addRequestHeader("Accept", "application/json, text/plain, */*"); method.addRequestHeader("Content-Type", "application/json"); String username = connProps.getProperty("user"); String password = connProps.getProperty("password"); String basicAuth = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes()); method.addRequestHeader("Authorization", "Basic " + basicAuth); }
From source file:org.apache.solr.servlet.CacheHeaderTest.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);/* w w w . j a v a2s . c o m*/ checkResponseBody(method, get); assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode()); Header head = get.getResponseHeader("Last-Modified"); assertNotNull("We got no Last-Modified header", head); Date lastModified = DateUtil.parseDate(head.getValue()); // If-Modified-Since tests get = getSelectMethod(method); get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date())); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 304 NotModified response with current date", 304, get.getStatusCode()); get = getSelectMethod(method); get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000))); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 OK response with If-Modified-Since in the past", 200, get.getStatusCode()); // If-Unmodified-Since tests get = getSelectMethod(method); get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000))); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 412 Precondition failed with If-Unmodified-Since in the past", 412, get.getStatusCode()); get = getSelectMethod(method); get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date())); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("Expected 200 OK response with If-Unmodified-Since and current date", 200, get.getStatusCode()); }
From source file:org.apache.solr.servlet.CacheHeaderTest.java
protected void doETag(String method) throws Exception { HttpMethodBase get = getSelectMethod(method); getClient().executeMethod(get);/*from w w w.j a va2s . com*/ checkResponseBody(method, get); assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode()); Header head = get.getResponseHeader("ETag"); assertNotNull("We got no ETag in the response", head); assertTrue("Not a valid ETag", head.getValue().startsWith("\"") && head.getValue().endsWith("\"")); String etag = head.getValue(); // 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()); // now we set matching ETags get = getSelectMethod(method); get.addRequestHeader("If-None-Match", "\"xyz1223\""); get.addRequestHeader("If-None-Match", "\"1231323423\", \"1211211\", " + etag); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-None-Match: Got no response 304 to matching ETag", 304, 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 304 for star ETag", 304, 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 412 in response to non matching ETag", 412, get.getStatusCode()); // now we set matching ETags get = getSelectMethod(method); get.addRequestHeader("If-Match", "\"xyz1223\""); get.addRequestHeader("If-Match", "\"1231323423\", \"1211211\", " + etag); getClient().executeMethod(get); checkResponseBody(method, get); assertEquals("If-Match: Got no response 200 to 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()); }