org.apache.commons.httpclient.cookie.CookiePolicy Java Examples

The following examples show how to use org.apache.commons.httpclient.cookie.CookiePolicy. 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: AbstractSubmarineServerTest.java    From submarine with Apache License 2.0 7 votes vote down vote up
protected static PostMethod httpPost(String path, String request, String mediaType, String user,
    String pwd) throws IOException {
  LOG.info("Connecting to {}", URL + path);

  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + path);
  postMethod.setRequestBody(request);
  postMethod.setRequestHeader("Content-type", mediaType);
  postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

  if (userAndPasswordAreNotBlank(user, pwd)) {
    postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }

  httpClient.executeMethod(postMethod);

  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());

  return postMethod;
}
 
Example #2
Source File: HttpState.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns an array of {@link Cookie cookies} in this HTTP 
 * state that match the given request parameters.
 * 
 * @param domain the request domain
 * @param port the request port
 * @param path the request path
 * @param secure <code>true</code> when using HTTPS
 * 
 * @return an array of {@link Cookie cookies}.
 * 
 * @see #getCookies()
 * 
 * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie)
 */
public synchronized Cookie[] getCookies(
    String domain, 
    int port, 
    String path, 
    boolean secure
) {
    LOG.trace("enter HttpState.getCookies(String, int, String, boolean)");

    CookieSpec matcher = CookiePolicy.getDefaultSpec();
    ArrayList list = new ArrayList(cookies.size());
    for (int i = 0, m = cookies.size(); i < m; i++) {
        Cookie cookie = (Cookie) (cookies.get(i));
        if (matcher.match(domain, port, path, secure, cookie)) {
            list.add(cookie);
        }
    }
    return (Cookie[]) (list.toArray(new Cookie[list.size()]));
}
 
Example #3
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public PutMethod createPut(final URI requestURI, final String accept, final boolean cookie) {
    final PutMethod method = new PutMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    method.addRequestHeader("Accept-Language", "en");
    return method;
}
 
Example #4
Source File: BaseHttp.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化
 *
 * @param client
 * @param method
 * @param headers
 * @param cookie
 * @throws UnsupportedEncodingException
 */
private static void init(HttpClient client, HttpMethod method, HashMap<String, String> header, BaseCookie[] cookie, String charset, int timeout) {
    client.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, charset);
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    method.setFollowRedirects(false);
    method.setRequestHeader("User-Agent", BaseHttp.DEFAULT_USER_AGENT);
    method.setRequestHeader("Cache-Control", "no-cache");
    method.setRequestHeader("Connection", "keep-alive");
    if (cookie != null) {
        String cookieString = "";
        for (BaseCookie ci : cookie) {
            try {
                cookieString += URLEncoder.encode(ci.getKey(), charset) + "=" + URLEncoder.encode(ci.getValue(), charset) + "; ";
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            }
        }
        method.setRequestHeader("Cookie", cookieString);
    } else {
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }
    if (header != null) {
        for (Entry<String, String> h : header.entrySet()) {
            method.setRequestHeader(h.getKey(), h.getValue());
        }
    }
}
 
Example #5
Source File: NeutronRestApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) {
    client = createHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    this.httpClazz = httpClazz;

    try {
        // Cast to ProtocolSocketFactory to avoid the deprecated constructor
        // with the SecureProtocolSocketFactory parameter
        Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
    } catch (IOException e) {
        s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
    }
}
 
Example #6
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public BigSwitchBcfApi() {
    _client = createHttpClient();
    _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {
        // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
        Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), _port));
    } catch (IOException e) {
        S_LOGGER.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
    }
}
 
Example #7
Source File: HTTPConnectionManagerSettings.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default <code>HTTPConnectionManagerSettings</code> instance.
 */
public HTTPConnectionManagerSettings()
{
    cookiePolicy = CookiePolicy.DEFAULT;
    defaultMaxConnectionsPerHost = DEFAULT_MAX_CONNECTIONS_HOST;
    maxTotalConnections = DEFAULT_MAX_TOTAL_CONNECTIONS;
    linger = -1;
    staleCheckingEnabled = true;
    tcpNoDelay = true;
}
 
Example #8
Source File: RestConsumer.java    From RestServices with Apache License 2.0 5 votes vote down vote up
public static List<Cookie> getResponseCookiesFromRequestResult(IContext context, RequestResult requestResult) throws MalformedURLException {
	if (requestResult == null)
		throw new IllegalArgumentException("No request result provided");
	
	List<Cookie> res = new ArrayList<Cookie>();
	JSONObject headers = new JSONObject(requestResult.get_ResponseHeaders());
	
	URL requestUrl = new URL(requestResult.getRequestUrl());
	CookieSpec spec = CookiePolicy.getDefaultSpec();
	
	if (headers.has("Set-Cookie")) {
		JSONArray cookies = headers.getJSONArray("Set-Cookie");
		for(int i = 0; i < cookies.length(); i++) {
			try {
				org.apache.commons.httpclient.Cookie[] innercookies = spec.parse(requestUrl.getHost(), requestUrl.getPort(), requestUrl.getPath(), "https".equals(requestUrl.getProtocol()), cookies.getString(i));
				for(org.apache.commons.httpclient.Cookie innercookie : innercookies) {
					Cookie cookie = new Cookie(context);
					cookie.setName(innercookie.getName());
					cookie.setValue(innercookie.getValue());
					cookie.setDomain(innercookie.getDomain());
					cookie.setPath(innercookie.getPath());
					cookie.setMaxAgeSeconds(innercookie.getExpiryDate() == null ? -1 : Math.round((innercookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000L));
					res.add(cookie);
				}
			} catch (Exception e) {
				RestServices.LOGCONSUME.warn("Failed to parse cookie: " + e.getMessage(), e);
			}
		}
	}
	
	return res;
}
 
Example #9
Source File: RestConsumer.java    From RestServices with Apache License 2.0 5 votes vote down vote up
public static void addCookieToNextRequest(Cookie cookie) {
	if (cookie == null || cookie.getName().isEmpty())
		throw new IllegalArgumentException();
	
	Map<String, String> headers = prepareNextHeadersMap();
	
	org.apache.commons.httpclient.Cookie rq = new org.apache.commons.httpclient.Cookie("", cookie.getName(), cookie.getValue());
	String cookiestr = CookiePolicy.getDefaultSpec().formatCookie(rq);
	
	if (!headers.containsKey("Cookie"))
		headers.put("Cookie", cookiestr);
	else
		headers.put("Cookie", headers.get("Cookie") + "; " + cookiestr);
}
 
Example #10
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public DeleteMethod createDelete(final URI requestURI, final String accept, final boolean cookie) {
    final DeleteMethod method = new DeleteMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    return method;
}
 
Example #11
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public PostMethod createPost(final URI requestURI, final String accept, final boolean cookie) {
    final PostMethod method = new PostMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    return method;
}
 
Example #12
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public PutMethod createPut(final URI requestURI, final String accept, final boolean cookie) {
    final PutMethod method = new PutMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    method.addRequestHeader("Accept-Language", "en");
    return method;
}
 
Example #13
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public void loginWithCookie(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
}
 
Example #14
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public HttpClient loginWithCookie(final String username, final String password) throws HttpException, IOException {
    final HttpClient c = getHttpClient();
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    return c;
}
 
Example #15
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public DeleteMethod createDelete(final URI requestURI, final String accept, final boolean cookie) {
    final DeleteMethod method = new DeleteMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    return method;
}
 
Example #16
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
public PostMethod createPost(final URI requestURI, final String accept, final boolean cookie) {
    final PostMethod method = new PostMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    return method;
}
 
Example #17
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public void loginWithCookie(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
}
 
Example #18
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public HttpClient loginWithCookie(final String username, final String password) throws HttpException, IOException {
    final HttpClient c = getHttpClient();
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    return c;
}
 
Example #19
Source File: YahooFinanceCSVInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  url = prepareURL();
  client = new HttpClient();
  method = new GetMethod(url);
  DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
}
 
Example #20
Source File: StockTickInput.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  url = prepareURL();
  client = new HttpClient();
  method = new GetMethod(url);
  DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
}
 
Example #21
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
protected static PostMethod httpPost(String path, String request, String user, String pwd)
    throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + path);
  postMethod.setRequestBody(request);
  postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  return postMethod;
}
 
Example #22
Source File: AbstractTestRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
protected static PostMethod httpPost(String path, String request, String user, String pwd)
        throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + path);
  postMethod.setRequestBody(request);
  postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  return postMethod;
}
 
Example #23
Source File: HttpMethodBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** 
 * Returns the actual cookie policy
 * 
 * @param state HTTP state. TODO: to be removed in the future
 * 
 * @return cookie spec
 */
private CookieSpec getCookieSpec(final HttpState state) {
    if (this.cookiespec == null) {
        int i = state.getCookiePolicy();
        if (i == -1) {
            this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy());
        } else {
            this.cookiespec = CookiePolicy.getSpecByPolicy(i);
        }
        this.cookiespec.setValidDateFormats(
                (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
    }
    return this.cookiespec;
}
 
Example #24
Source File: HttpMethodParams.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns {@link CookiePolicy cookie policy} to be used by the 
 * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} 
 * this collection of parameters applies to. 
 *
 * @return {@link CookiePolicy cookie policy}
 */
public String getCookiePolicy() { 
    Object param = getParameter(COOKIE_POLICY);
    if (param == null) {
        return CookiePolicy.DEFAULT;
    }
    return (String)param;
}
 
Example #25
Source File: Cookie.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Return a textual representation of the cookie.
 * 
 * @return string.
 */
public String toExternalForm() {
    CookieSpec spec = null;
    if (getVersion() > 0) {
        spec = CookiePolicy.getDefaultSpec(); 
    } else {
        spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); 
    }
    return spec.formatCookie(this); 
}
 
Example #26
Source File: ServerStatusChecker.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Basic constructor sets the listener to notify when
 * servers goes down/up. Also sets the polling time
 * which decides how long we wait between doing checks.
 * 
 * @param listener The listener
 * @param pollingTime The time we wait between checks, in milliseconds
 */
public ServerStatusChecker(ServerStatusListener listener, long pollingTime) {
    this.listener = listener;
    this.pollingTime = Math.max(30*1000, pollingTime);
    setPriority(Thread.NORM_PRIORITY-1);
    setDaemon(true);
    
    online = new LinkedList();
    offline = new LinkedList();
    httpClient = new HttpClient(); 
    httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false);
    httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
 
Example #27
Source File: HttpMethodBase.java    From http4e with Apache License 2.0 5 votes vote down vote up
/** 
 * Returns the actual cookie policy
 * 
 * @param state HTTP state. TODO: to be removed in the future
 * 
 * @return cookie spec
 */
private CookieSpec getCookieSpec(final HttpState state) {
    if (this.cookiespec == null) {
        int i = state.getCookiePolicy();
        if (i == -1) {
            this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy());
        } else {
            this.cookiespec = CookiePolicy.getSpecByPolicy(i);
        }
        this.cookiespec.setValidDateFormats(
                (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
    }
    return this.cookiespec;
}
 
Example #28
Source File: HttpClientUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化HttpClient对象
 */
public static HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    
    // 设置Cookie处理策略,RFC_2109是支持较普遍的一个,还有其他cookie协议
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    
    // 设置超时时间
    MultiThreadedHttpConnectionManager hcm = new MultiThreadedHttpConnectionManager();
    hcm.getParams().setConnectionTimeout(HTTP_REQUEST_TIMEOUT);
    client.setHttpConnectionManager(hcm);
    return client;
}
 
Example #29
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 3 votes vote down vote up
/**
 * Return a GetMethod
 * 
 * @param requestURI
 * @param accept
 *            accepted mime-type
 * @param cookie
 *            allow cookie or not
 * @return
 */
public GetMethod createGet(final URI requestURI, final String accept, final boolean cookie) {
    final GetMethod method = new GetMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    method.addRequestHeader("Accept", accept);
    return method;
}
 
Example #30
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 3 votes vote down vote up
/**
 * Return a GetMethod
 * 
 * @param requestURI
 * @param accept
 *            accepted mime-type
 * @param cookie
 *            allow cookie or not
 * @return
 */
public GetMethod createGet(final URI requestURI, final String accept, final boolean cookie) {
    final GetMethod method = new GetMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }
    method.addRequestHeader("Accept", accept);
    return method;
}