Java Code Examples for org.apache.commons.httpclient.HttpMethod#addRequestHeader()

The following examples show how to use org.apache.commons.httpclient.HttpMethod#addRequestHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // 设置HttpMethod的参数
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());
}
 
Example 2
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // 设置HttpMethod的参数
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());
}
 
Example 3
Source File: RequestHandlerBase.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * 
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
        
        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            } 
        } 
    } 
    
    setProxySpecificHeaders(method, request);
}
 
Example 4
Source File: HttpUtil.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static ServerStatus configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException {
	method.addRequestHeader(new Header("Accept", "application/json"));
	method.addRequestHeader(new Header("Content-Type", "application/json"));
	//set default socket timeout for connection
	HttpMethodParams params = method.getParams();
	params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
	params.setContentCharset("UTF-8");
	method.setParams(params);
	if (cloud.getAccessToken() != null){
		method.addRequestHeader(new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token")));
		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
	}
	
	JSONObject errorJSON = new JSONObject();
	try {
		errorJSON.put(CFProtocolConstants.V2_KEY_REGION_ID, cloud.getRegion());
		errorJSON.put(CFProtocolConstants.V2_KEY_REGION_NAME, cloud.getRegionName() != null ? cloud.getRegionName() : "");
		errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_CODE, "CF-NotAuthenticated");
		errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_DESCRIPTION, "Not authenticated");
	} catch (JSONException e) {
		// do nothing
	}
	return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated", errorJSON, null);
}
 
Example 5
Source File: Proxy.java    From odo with Apache License 2.0 6 votes vote down vote up
/**
 * Apply any applicable header overrides to request
 *
 * @param httpMethodProxyRequest
 * @throws Exception
 */
private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {
    RequestInformation requestInfo = requestInformation.get();
    for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {
        List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();
        for (EnabledEndpoint endpoint : points) {
            if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {
                httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),
                                                        endpoint.getArguments()[1].toString());
                requestInfo.modified = true;
            } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {
                httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());
                requestInfo.modified = true;
            }
        }
    }
}
 
Example 6
Source File: RESTMetadataProvider.java    From vind with Apache License 2.0 5 votes vote down vote up
@Override
public Document getDocument(Document document, DocumentFactory factory) throws IOException {

    HttpMethod request = new GetMethod(baseURL);

    request.addRequestHeader("Authorization", String.format("Bearer %s", bearerToken)); //TODO
    request.setPath(path + document.getId());

    int status = client.executeMethod(request);

    if(status == 200) {

        JsonNode json = mapper.readValue(request.getResponseBody(), JsonNode.class);

        for(FieldDescriptor descriptor : factory.listFields()) {

            try {
                Object value = getValue(json, descriptor);
                if(value != null) {
                    document.setValue(descriptor, value);
                } else LOG.warn("No data found for id {}", document.getId());
            } catch (IOException e) {
                LOG.warn("Cannot use data for id {}: {}", document.getId(), e.getMessage());
            }
        }

        return document;

    } else throw new IOException(request.getStatusText());
}
 
Example 7
Source File: BusinessJob.java    From http4e with Apache License 2.0 5 votes vote down vote up
private void addHeaders( HttpMethod httpMethod, Map<String, String> parameterizedMap){
   for (Iterator it = model.getHeaders().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
      httpMethod.addRequestHeader(key, parameterizedVal);
   }

   // add User-Agent: ProjectName
   boolean userAgentExist = false;
   Header[] hhh = httpMethod.getRequestHeaders();
   for (int i = 0; i < hhh.length; i++) {
      Header h = hhh[i];
      if (CoreConstants.HEADER_USER_AGENT.equalsIgnoreCase(h.getName())) {
         userAgentExist = true;
      }
   }

   if (!userAgentExist) {
      httpMethod.addRequestHeader(CoreConstants.HEADER_USER_AGENT, CoreMessages.PLUGIN_NAME_SHORT + "/" + CoreMessages.VERSION);
   }
}
 
Example 8
Source File: MaxForwardRequestHandler.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Will write all the headers included in the request to the method.
 * The difference between this method and setHeaders in BasicRequestHandler
 * is that the BasicRequestHandler will also add Via, x-forwarded-for, etc.
 * These "special" headers should not be added when the proxy is target
 * directly with a Max-Forwards: 0 headers.
 * @param method The method to write to
 * @param request The incoming request
 * @see RequestHandlerBase#setHeaders(HttpMethod, HttpServletRequest)
 */
private void setAllHeaders(HttpMethod method, HttpServletRequest request) {
    Enumeration headers = request.getHeaderNames();
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        Enumeration value = request.getHeaders(name);
        
        while (value.hasMoreElements()) {
            method.addRequestHeader(name, (String) value.nextElement());
        }

    } 
}
 
Example 9
Source File: HttpAuthenticator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static boolean doAuthenticateDefault(
    HttpMethod method, 
    HttpConnection conn,
    HttpState state, 
    boolean proxy)
  throws AuthenticationException {
    if (method == null) {
        throw new IllegalArgumentException("HTTP method may not be null");
    }
    if (state == null) {
        throw new IllegalArgumentException("HTTP state may not be null");
    }
    String host = null;
    if (conn != null) {
        host = proxy ? conn.getProxyHost() : conn.getHost();
    }
    Credentials credentials = proxy 
        ? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
    if (credentials == null) {
        return false;
    }
    if (!(credentials instanceof UsernamePasswordCredentials)) {
        throw new InvalidCredentialsException(
         "Credentials cannot be used for basic authentication: " 
          + credentials.toString());
    }
    String auth = BasicScheme.authenticate(
        (UsernamePasswordCredentials) credentials,
        method.getParams().getCredentialCharset());
    if (auth != null) {
        String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
        Header header = new Header(s, auth, true);
        method.addRequestHeader(header);
        return true;
    } else {
        return false;
    }
}
 
Example 10
Source File: CloudMetadataScanner.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static HttpMethod createRequestMethod(
        HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException {
    HttpMethod httpMethod = new ZapGetMethod();
    httpMethod.setURI(header.getURI());
    httpMethod.setParams(params);
    params.setVersion(HttpVersion.HTTP_1_1);

    String msg = header.getHeadersAsString();

    String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg);
    String token = null;
    String name = null;
    String value = null;

    int pos = 0;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
 
Example 11
Source File: HttpClientExecuteInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst, final Method method, final Object[] allArguments,
    final Class<?>[] argumentsTypes, final MethodInterceptResult result) throws Throwable {

    final HttpClient client = (HttpClient) objInst;

    HostConfiguration hostConfiguration = (HostConfiguration) allArguments[0];
    if (hostConfiguration == null) {
        hostConfiguration = client.getHostConfiguration();
    }

    final HttpMethod httpMethod = (HttpMethod) allArguments[1];
    final String remotePeer = httpMethod.getURI().getHost() + ":" + httpMethod.getURI().getPort();

    final URI uri = httpMethod.getURI();
    final String requestURI = getRequestURI(uri);

    final ContextCarrier contextCarrier = new ContextCarrier();
    final AbstractSpan span = ContextManager.createExitSpan(requestURI, contextCarrier, remotePeer);

    span.setComponent(ComponentsDefine.HTTPCLIENT);
    Tags.URL.set(span, uri.toString());
    Tags.HTTP.METHOD.set(span, httpMethod.getName());
    SpanLayer.asHttp(span);

    for (CarrierItem next = contextCarrier.items(); next.hasNext(); ) {
        next = next.next();
        httpMethod.addRequestHeader(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example 12
Source File: TestRailClient.java    From testrail-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private HttpClient setUpHttpClient(HttpMethod method) {
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setAuthenticationPreemptive(true);
    httpclient.getState().setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials(this.user, this.password)
    );
    method.setDoAuthentication(true);
    method.addRequestHeader("Content-Type", "application/json");
    return httpclient;
}
 
Example 13
Source File: WebdavFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a Method object.
 *
 * @param method the HttpMethod.
 * @throws FileSystemException if an error occurs encoding the uri.
 * @throws URIException if the URI is in error.
 */
@Override
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
    method.addRequestHeader("Cache-control", "no-cache");
    method.addRequestHeader("Cache-store", "no-store");
    method.addRequestHeader("Pragma", "no-cache");
    method.addRequestHeader("Expires", "0");
}
 
Example 14
Source File: HttpUtil.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 *
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or
 *            <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '{}'", method.getURI());
        } catch (URIException e) {
            logger.debug("{}", e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.debug("Method failed: {}", method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("{}", responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}
 
Example 15
Source File: CrucibleSessionImpl.java    From Crucible4IDEA with MIT License 4 votes vote down vote up
protected void adjustHttpHeader(@NotNull final HttpMethod method) {
  method.addRequestHeader(new Header("Authorization", getAuthHeaderValue()));
  method.addRequestHeader(new Header("accept", "application/json"));
}
 
Example 16
Source File: ChatterTools.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpMethod addHeaders(HttpMethod method, ChatterAuthToken token) {
    method.setRequestHeader("Authorization", "OAuth " + token.getAccessToken());
    method.addRequestHeader("X-PrettyPrint", "1");

    return method;
}
 
Example 17
Source File: Proxy.java    From odo with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a request through Odo processing
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse, History history) {
    try {
        RequestInformation requestInfo = requestInformation.get();

        // Execute the request

        // set virtual host so the server knows how to direct the request
        // If the host header exists then this uses that value
        // Otherwise the hostname from the URL is used
        processVirtualHostName(httpMethodProxyRequest, httpServletRequest);
        cullDisabledPaths();

        // check for existence of ODO_PROXY_HEADER
        // finding it indicates a bad loop back through the proxy
        if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {
            logger.error("Request has looped back into the proxy.  This will not be executed: {}", httpServletRequest.getRequestURL());
            return;
        }

        // set ODO_PROXY_HEADER
        httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, "proxied");

        requestInfo.blockRequest = hasRequestBlock();
        PluginResponse responseWrapper = new PluginResponse(httpServletResponse);
        requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);

        if (!requestInfo.blockRequest) {
            logger.info("Sending request to server");

            history.setModified(requestInfo.modified);
            history.setRequestSent(true);

            executeRequest(httpMethodProxyRequest,
                           httpServletRequest,
                           responseWrapper,
                           history);
        } else {
            history.setRequestSent(false);
        }

        logOriginalResponseHistory(responseWrapper, history);
        applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);
        // store history
        history.setModified(requestInfo.modified);
        logRequestHistory(httpMethodProxyRequest, responseWrapper, history);

        writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: Proxy.java    From odo with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request
 *
 * @param httpServletRequest The request object representing the client's request to the
 * servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,
                                    HttpMethod httpMethodProxyRequest) throws Exception {
    RequestInformation requestInfo = requestInformation.get();
    String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());
    // Get an Enumeration of all of the header names sent by the client
    Boolean stripTransferEncoding = false;
    Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {
            // don't add this header
            continue;
        }

        // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE
        if (stringHeaderName.equalsIgnoreCase("ODO-POST-TYPE") &&
            httpServletRequest.getHeader("ODO-POST-TYPE").startsWith("content-length:")) {
            stripTransferEncoding = true;
        }

        logger.info("Current header: {}", stringHeaderName);
        // As per the Java Servlet API 2.5 documentation:
        // Some headers, such as Accept-Language can be sent by clients
        // as several headers each with a different value rather than
        // sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the
        // client
        Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);

        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&
                requestInfo.handle) {
                String hostValue = getHostHeaderForHost(hostName);
                if (hostValue != null) {
                    stringHeaderValue = hostValue;
                }
            }

            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.addRequestHeader(header);
        }
    }

    // this strips transfer encoding headers and adds in the appropriate content-length header
    // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)
    if (stripTransferEncoding) {
        httpMethodProxyRequest.removeRequestHeader("transfer-encoding");

        // add content length back in based on the ODO information
        String contentLengthHint = httpServletRequest.getHeader("ODO-POST-TYPE");
        String[] contentLengthParts = contentLengthHint.split(":");
        httpMethodProxyRequest.addRequestHeader("content-length", contentLengthParts[1]);

        // remove the odo-post-type header
        httpMethodProxyRequest.removeRequestHeader("ODO-POST-TYPE");
    }

    // bail if we aren't fully handling this request
    if (!requestInfo.handle) {
        return;
    }

    // deal with header overrides for the request
    processRequestHeaderOverrides(httpMethodProxyRequest);
}
 
Example 19
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * @param tuReq
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}
 
Example 20
Source File: Http3SignatureAuthScheme.java    From httpsig-java with The Unlicense 4 votes vote down vote up
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    if (credentials instanceof SignerCredentials) {
        SignerCredentials creds = (SignerCredentials) credentials;
        String headers = this.getParameter(Constants.HEADERS);
        String algorithms = this.getParameter(Constants.ALGORITHMS);

        Challenge challenge = new Challenge(this.getRealm(), Constants.parseTokens(headers), Challenge.parseAlgorithms(algorithms));

        Signer signer = creds.getSigner();
        if (signer != null) {

            if (this.rotate) {
                this.rotate = false;
                if (!signer.rotateKeys(challenge, this.lastAuthz)) {
                    signer.rotateKeys(challenge);
                    return null;
                }
            }

            RequestContent.Builder sigBuilder = new RequestContent.Builder();

            sigBuilder.setRequestTarget(method.getName(), method.getPath() + (method.getQueryString() != null ? "?" + method.getQueryString() : ""));

            for (Header header : method.getRequestHeaders()) {
                sigBuilder.addHeader(header.getName(), header.getValue());
            }

            if (sigBuilder.build().getDate() == null) {
                sigBuilder.addDateNow();
                method.addRequestHeader(Constants.HEADER_DATE, sigBuilder.build().getDate());
            }

            Authorization authorization = creds.getSigner().sign(sigBuilder.build());
            this.lastAuthz = authorization;
            if (authorization != null) {
                return authorization.getHeaderValue();
            }
        }
    }

    return null;
}