List of usage examples for org.apache.commons.httpclient HttpMethod getRequestHeader
public abstract Header getRequestHeader(String paramString);
From source file:davmail.http.SpNegoScheme.java
/** * Produces Negotiate authorization string for the given set of * {@link Credentials}.//from ww w . j a v a2s .c om * * @param credentials The set of credentials to be used for authentication * @param httpMethod The method being authenticated * @return an Negotiate authorization string * @throws org.apache.commons.httpclient.auth.InvalidCredentialsException * if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure */ public String authenticate(Credentials credentials, HttpMethod httpMethod) throws AuthenticationException { if (this.state == UNINITIATED) { throw new IllegalStateException("Negotiate authentication process has not been initiated"); } String host = null; try { host = httpMethod.getURI().getHost(); } catch (URIException e) { // ignore } if (host == null) { Header header = httpMethod.getRequestHeader("Host"); if (header != null) { host = header.getValue(); if (host.indexOf(':') >= 0) { host = host.substring(0, host.indexOf(':')); } } } if (host == null) { throw new IllegalStateException("Negotiate authentication failed: empty host"); } // no credentials needed String response; try { if (this.state == INITIATED || this.state == FAILED) { // send initial token to server response = EncodingUtil.getAsciiString( Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, new byte[0]))); this.state = TYPE1_MSG_GENERATED; } else { // send challenge response response = EncodingUtil.getAsciiString( Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, serverToken))); this.state = TYPE3_MSG_GENERATED; } } catch (GSSException gsse) { state = FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new CredentialsNotAvailableException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthChallengeException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage(), gsse); } catch (LoginException e) { state = FAILED; throw new InvalidCredentialsException(e.getMessage(), e); } return "Negotiate " + response; }
From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java
/**download methods*/ @Override/* w w w .j a v a 2 s.co m*/ protected byte[] downloadFile() { this.setRunning(true); byte[] result = null; InputStream is = null; ByteArrayOutputStream bas = null; String url = this.getURL(); PLFileDownloaderListener listener = this.getListener(); boolean hasListener = (listener != null); int responseCode = -1; long startTime = System.currentTimeMillis(); // HttpClient instance HttpClient client = new HttpClient(); // Method instance HttpMethod method = new GetMethod(url); // Method parameters HttpMethodParams methodParams = method.getParams(); methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android"); methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false)); try { // Execute the method responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) throw new IOException(method.getStatusText()); // Get content length Header header = method.getRequestHeader("Content-Length"); long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1); if (this.isRunning()) { if (hasListener) listener.didBeginDownload(url, startTime); } else throw new PLRequestInvalidatedException(url); // Get response body as stream is = method.getResponseBodyAsStream(); bas = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int length = 0, total = 0; // Read stream while ((length = is.read(buffer)) != -1) { if (this.isRunning()) { bas.write(buffer, 0, length); total += length; if (hasListener) listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f)); } else throw new PLRequestInvalidatedException(url); } if (total == 0) throw new IOException("Request data has invalid size (0)"); // Get data if (this.isRunning()) { result = bas.toByteArray(); if (hasListener) listener.didEndDownload(url, result, System.currentTimeMillis() - startTime); } else throw new PLRequestInvalidatedException(url); } catch (Throwable e) { if (this.isRunning()) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); if (hasListener) listener.didErrorDownload(url, e.toString(), responseCode, result); } } finally { if (bas != null) { try { bas.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } if (is != null) { try { is.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } // Release the connection method.releaseConnection(); } this.setRunning(false); return result; }
From source file:com.zimbra.cs.servlet.ZimbraServlet.java
public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, HttpState state) throws IOException, ServiceException { // create an HTTP client with the same cookies javax.servlet.http.Cookie cookies[] = req.getCookies(); String hostname = method.getURI().getHost(); boolean hasZMAuth = hasZimbraAuthCookie(state); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth) continue; state.addCookie(//from w w w . ja v a2 s .co m new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false)); } } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); if (state != null) client.setState(state); int hopcount = 0; for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) { String hname = (String) enm.nextElement(), hlc = hname.toLowerCase(); if (hlc.equals("x-zimbra-hopcount")) try { hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0); } catch (NumberFormatException e) { } else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization")) method.addRequestHeader(hname, req.getHeader(hname)); } if (hopcount >= MAX_PROXY_HOPCOUNT) throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req)); method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1)); if (method.getRequestHeader("X-Zimbra-Orig-Url") == null) method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString()); String ua = req.getHeader("User-Agent"); if (ua != null) method.setRequestHeader("User-Agent", ua); // dispatch the request and copy over the results int statusCode = -1; for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) { statusCode = HttpClientUtil.executeMethod(client, method); } if (statusCode == -1) { resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached"); return; } else if (statusCode >= 300) { resp.sendError(statusCode, method.getStatusText()); return; } Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String hname = headers[i].getName(), hlc = hname.toLowerCase(); if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-")) resp.addHeader(hname, headers[i].getValue()); } InputStream responseStream = method.getResponseBodyAsStream(); if (responseStream == null || resp.getOutputStream() == null) return; ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false); }
From source file:com.groupon.odo.Proxy.java
/** * Set virtual host so the server can direct the request. Value is the host header if it is set, otherwise * use the hostname from the original request. * * @param httpMethodProxyRequest/*from ww w . j a v a2s. c o m*/ * @param httpServletRequest */ private void processVirtualHostName(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest) { String virtualHostName; if (httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME) != null) { virtualHostName = httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME).getValue(); } else { virtualHostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString()); } httpMethodProxyRequest.getParams().setVirtualHost(virtualHostName); }
From source file:ir.keloud.android.lib.common.KeloudClient.java
private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException { int redirectionsCount = 0; while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location == null) { location = method.getResponseHeader("location"); }// w ww . j a va 2 s.c o m if (location != null) { Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue()); // Release the connection to avoid reach the max number of connections per host // due to it will be set a different url exhaustResponse(method.getResponseBodyAsStream()); method.releaseConnection(); method.setURI(new URI(location.getValue(), true)); Header destination = method.getRequestHeader("Destination"); if (destination == null) { destination = method.getRequestHeader("destination"); } if (destination != null) { String locationStr = location.getValue(); int suffixIndex = locationStr .lastIndexOf((mCredentials instanceof KeloudBearerCredentials) ? AccountUtils.ODAV_PATH : AccountUtils.WEBDAV_PATH_4_0); String redirectionBase = locationStr.substring(0, suffixIndex); String destinationStr = destination.getValue(); String destinationPath = destinationStr.substring(mBaseUri.toString().length()); String redirectedDestination = redirectionBase + destinationPath; destination.setValue(redirectedDestination); method.setRequestHeader(destination); } status = super.executeMethod(method); redirectionsCount++; } else { Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); status = HttpStatus.SC_NOT_FOUND; } } return status; }
From source file:com.owncloud.android.lib.common.OwnCloudClient.java
private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException { int redirectionsCount = 0; while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location == null) { location = method.getResponseHeader("location"); }/*from w w w .java2s .co m*/ if (location != null) { Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue()); // Release the connection to avoid reach the max number of connections per host // due to it will be set a different url exhaustResponse(method.getResponseBodyAsStream()); method.releaseConnection(); method.setURI(new URI(location.getValue(), true)); Header destination = method.getRequestHeader("Destination"); if (destination == null) { destination = method.getRequestHeader("destination"); } if (destination != null) { String locationStr = location.getValue(); int suffixIndex = locationStr.lastIndexOf( (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH : AccountUtils.WEBDAV_PATH_4_0); String redirectionBase = locationStr.substring(0, suffixIndex); String destinationStr = destination.getValue(); String destinationPath = destinationStr.substring(mBaseUri.toString().length()); String redirectedDestination = redirectionBase + destinationPath; destination.setValue(redirectedDestination); method.setRequestHeader(destination); } status = super.executeMethod(method); redirectionsCount++; } else { Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); status = HttpStatus.SC_NOT_FOUND; } } return status; }
From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java
public RedirectionPath followRedirection(HttpMethod method) throws IOException { int redirectionsCount = 0; int status = method.getStatusCode(); RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT); while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location == null) { location = method.getResponseHeader("location"); }/*from w ww . ja va 2s . co m*/ if (location != null) { Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue()); String locationStr = location.getValue(); result.addLocation(locationStr); // Release the connection to avoid reach the max number of connections per host // due to it will be set a different url exhaustResponse(method.getResponseBodyAsStream()); method.releaseConnection(); method.setURI(new URI(locationStr, true)); Header destination = method.getRequestHeader("Destination"); if (destination == null) { destination = method.getRequestHeader("destination"); } if (destination != null) { int suffixIndex = locationStr.lastIndexOf( (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH : AccountUtils.WEBDAV_PATH_4_0); String redirectionBase = locationStr.substring(0, suffixIndex); String destinationStr = destination.getValue(); String destinationPath = destinationStr.substring(mBaseUri.toString().length()); String redirectedDestination = redirectionBase + destinationPath; destination.setValue(redirectedDestination); method.setRequestHeader(destination); } status = super.executeMethod(method); result.addStatus(status); redirectionsCount++; } else { Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); status = HttpStatus.SC_NOT_FOUND; } } return result; }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
protected int doExecuteMethod(final HttpMethod method, Context context) throws ConnectionException, URIException, MalformedURLException { int statuscode = -1; // Tells the method to automatically handle authentication. method.setDoAuthentication(true);/*from w ww. jav a 2 s. c o m*/ // Tells the method to automatically handle redirection. method.setFollowRedirects(false); HttpPool httpPool = ((AbstractHttpTransaction) context.transaction).getHttpPool(); HttpClient httpClient = context.getHttpClient3(httpPool); try { // Display the cookies if (handleCookie) { Cookie[] cookies = httpState.getCookies(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans.trace( "(HttpConnector) HttpClient request cookies:" + Arrays.asList(cookies).toString()); } forwardHeader(new HeaderForwarder() { public void add(String name, String value, String forwardPolicy) { if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_IGNORE.equals(forwardPolicy)) { Header exHeader = method.getRequestHeader(name); if (exHeader != null) { // Nothing to do Engine.logEngine.debug("(WebViewer) Forwarding header '" + name + "' has been ignored due to forward policy"); } else { method.setRequestHeader(name, value); Engine.logEngine.debug("(WebViewer) Header forwarded and added: " + name + "=" + value); } } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_REPLACE.equals(forwardPolicy)) { method.setRequestHeader(name, value); Engine.logEngine.debug("(WebViewer) Header forwarded and replaced: " + name + "=" + value); } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_MERGE.equals(forwardPolicy)) { Header exHeader = method.getRequestHeader(name); if (exHeader != null) value = exHeader.getValue() + ", " + value; method.setRequestHeader(name, value); Engine.logEngine.debug("(WebViewer) Header forwarded and merged: " + name + "=" + value); } } }); // handle oAuthSignatures if any if (oAuthKey != null && oAuthSecret != null && oAuthToken != null && oAuthTokenSecret != null) { oAuthConsumer = new HttpOAuthConsumer(oAuthKey, oAuthSecret, hostConfiguration); oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret); oAuthConsumer.sign(method); oAuthConsumer = null; } HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool); hostConfiguration.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000); hostConfiguration.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000); Engine.logBeans.debug("(HttpConnector) HttpClient: executing method..."); statuscode = httpClient.executeMethod(hostConfiguration, method, httpState); Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull"); // Display the cookies if (handleCookie) { Cookie[] cookies = httpState.getCookies(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans.trace( "(HttpConnector) HttpClient response cookies:" + Arrays.asList(cookies).toString()); } } catch (SocketTimeoutException e) { throw new ConnectionException( "Timeout reached (" + context.requestedObject.getResponseTimeout() + " sec)"); } catch (IOException e) { if (!context.requestedObject.runningThread.bContinue) return statuscode; try { HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool); Engine.logBeans.warn("(HttpConnector) HttpClient: connection error to " + sUrl + ": " + e.getMessage() + "; retrying method"); statuscode = httpClient.executeMethod(hostConfiguration, method, httpState); Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull"); } catch (IOException ee) { throw new ConnectionException("Connection error to " + sUrl, ee); } } catch (OAuthException eee) { throw new ConnectionException("OAuth Connection error to " + sUrl, eee); } return statuscode; }
From source file:org.mozilla.zest.impl.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;/*w ww.j a v a2s . co m*/ case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after Header contentType = method.getRequestHeader("Content-Type"); RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); if (contentType != null) { method.setRequestHeader(contentType); } } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) { // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests method = new GetMethod(method.getResponseHeader("Location").getValue()); // Just in case there are multiple redirects method.setFollowRedirects(req.isFollowRedirects()); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } } return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.mule.transport.as2.As2MessageDispatcher.java
protected HttpMethod execute(MuleEvent event, HttpMethod httpMethod) throws Exception { logger.debug("DBG: inside " + getClass() + ".execute()"); // TODO set connection timeout buffer etc try {/* w w w .j av a 2 s .co m*/ String endpointAddress = endpoint.getEndpointURI().getAddress(); URI uri = new URI(endpointAddress.replaceFirst("as2", "http")); this.processCookies(event); this.processMuleSession(event, httpMethod); this.setAS2Headers(event, httpMethod); logger.debug("DBG: Contenty Type is: " + httpMethod.getRequestHeader(AS2Constants.HEADER_CONTENT_TYPE)); // TODO can we use the return code for better reporting? // client.setConnectionTimeout(20000); client.executeMethod(getHostConfig(uri), httpMethod); return httpMethod; } catch (IOException e) { // TODO employ dispatcher reconnection strategy at this point logger.error(e, e); throw new DispatchException(event, getEndpoint(), e); } catch (Exception e) { logger.error(e, e); throw new DispatchException(event, getEndpoint(), e); } }