Java Code Examples for java.net.HttpCookie#getValue()

The following examples show how to use java.net.HttpCookie#getValue() . 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: TransportableHttpCookie.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
public static List<TransportableHttpCookie> from(URL url, List<HttpCookieWithId> list) {
    List<TransportableHttpCookie> result = new ArrayList<>(list.size());
    for (HttpCookieWithId hcwi : list) {
        HttpCookie cookie = hcwi.httpCookie;
        TransportableHttpCookie thc = new TransportableHttpCookie();
        thc.name = cookie.getName();
        thc.value = cookie.getValue();
        thc.comment = cookie.getComment();
        thc.commentURL = cookie.getCommentURL();
        thc.discard = cookie.getDiscard();
        thc.domain = cookie.getDomain();
        thc.maxAge = cookie.getMaxAge();
        thc.path = cookie.getPath();
        thc.portList = cookie.getPortlist();
        thc.secure = cookie.getSecure();
        thc.version = cookie.getVersion();
        thc.url = url.toString();
        result.add(thc);
    }
    return result;
}
 
Example 2
Source File: AuthCookie.java    From utexas-utilities with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a login request with the AuthCookie's OkHttpClient. This should only be called
 * when persistent login is activated.
 * @param request Request to execute
 * @return true if the cookie was set successfully, false if the cookie was not set
 * @throws IOException
 */
protected boolean performLogin(Request request) throws IOException {
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Bad response code: " + response + " during login.");
    }
    response.body().close();
    CookieManager cm = (CookieManager) CookieHandler.getDefault();
    List<HttpCookie> cookies = cm.getCookieStore().getCookies();
    for (HttpCookie cookie : cookies) {
        String cookieVal = cookie.getValue();
        if (cookie.getName().equals(authCookieKey)) {
            setAuthCookieVal(cookieVal);
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: AuthenticatedWebSocket.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String onConnect(Session session) {
    for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) {
        if ("auth-token".equals(cookie.getName())) {
            String authToken = cookie.getValue();
            TokenAuthenticator authenticator = getAuthenticator();
            org.hibernate.Session hSession = sessionFactory.openSession();
            ManagedSessionContext.bind(hSession);
            Optional<BasicToken> token;
            try {
                token = authenticator.authenticate(authToken);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return null;
            }
            if (!token.isPresent()) {
                return null;
            }
            hSession.close();
            return token.get().getUserId();
        }
    }
    return null;
}
 
Example 4
Source File: CookieEntity.java    From NoHttp with Apache License 2.0 6 votes vote down vote up
/**
 * Cookie building database entities.
 *
 * @param uri    cookie corresponding uri.
 * @param cookie cookie.
 */
public CookieEntity(URI uri, HttpCookie cookie) {
    this.uri = uri == null ? null : uri.toString();
    this.name = cookie.getName();
    this.value = cookie.getValue();
    this.comment = cookie.getComment();
    this.commentURL = cookie.getCommentURL();
    this.discard = cookie.getDiscard();
    this.domain = cookie.getDomain();
    long maxAge = cookie.getMaxAge();
    if (maxAge != -1 && maxAge > 0) {
        this.expiry = (maxAge * 1000L) + System.currentTimeMillis();
        if (this.expiry < 0L) // 溢出
            this.expiry = HeaderUtils.getMaxExpiryMillis();
    } else
        this.expiry = -1L;

    this.path = cookie.getPath();
    if (!TextUtils.isEmpty(path) && path.length() > 1 && path.endsWith("/")) {
        this.path = path.substring(0, path.length() - 1);
    }
    this.portList = cookie.getPortlist();
    this.secure = cookie.getSecure();
    this.version = cookie.getVersion();
}
 
Example 5
Source File: ApiProxyServlet.java    From onboard with Apache License 2.0 6 votes vote down vote up
/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and renames cookie to avoid
 * collisions.
 */
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = getServletContext().getServletContextName();
    if (path == null) {
        path = "";
    }
    path += servletRequest.getServletPath();

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}
 
Example 6
Source File: CookiesUtils.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
public String resetCookies(List<String> cookieStrings) {
	String result = null;
	for (String cookieString : cookieStrings) {
		List<HttpCookie> parse = HttpCookie.parse(cookieString);
		for (HttpCookie httpCookie : parse) {
			if(StringUtils.isNoneBlank(httpCookie.getValue())) {
				String cookie = httpCookie.getName()+"="+httpCookie.getValue();
				if(result==null) {
					result = cookie;
				} else {
					result = result + " ; " + cookie;
				}
			}
		}
	}
	return result;
}
 
Example 7
Source File: NMBApplication.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
public static void updateCookies(Context context) {
    SimpleCookieStore cookieStore = NMBApplication.getSimpleCookieStore(context);

    URL url = ACSite.getInstance().getSiteUrl();
    HttpCookieWithId hcwi = cookieStore.getCookie(url, "userId");
    if (hcwi != null) {
        HttpCookie oldCookie = hcwi.httpCookie;
        cookieStore.remove(url, oldCookie);

        HttpCookie newCookie = new HttpCookie("userhash", oldCookie.getValue());
        newCookie.setComment(oldCookie.getComment());
        newCookie.setCommentURL(oldCookie.getCommentURL());
        newCookie.setDiscard(oldCookie.getDiscard());
        newCookie.setDomain(oldCookie.getDomain());
        newCookie.setMaxAge(oldCookie.getMaxAge());
        newCookie.setPath(oldCookie.getPath());
        newCookie.setPortlist(oldCookie.getPortlist());
        newCookie.setSecure(oldCookie.getSecure());
        newCookie.setVersion(oldCookie.getVersion());

        cookieStore.add(url, newCookie);
    }
}
 
Example 8
Source File: HttpProxy.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Copy cookie from the proxy to the servlet client.
 * Replaces cookie path to local path and renames cookie to avoid collisions.
 */
private void copyProxyCookie(HttpServletRequest servletRequest,
                             HttpServletResponse servletResponse, Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
    for (int i = 0, l = cookies.size(); i < l; i++) {
        HttpCookie cookie = cookies.get(i);
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}
 
Example 9
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Authentication with google account
 * @param cookies cookies list keys from google auth
 * @param login username associated to zds login
 * @param id user id on ZdS associated to login
 */
public void authToGoogle(List<HttpCookie> cookies, String login, String id) {
    if(login != null && id != null) {
        this.login = login;
        this.idUser = id;
        log.info("L'identifiant de l'utilisateur " + this.login + " est : " + idUser);
        cookieStore = new BasicCookieStore();
        for(HttpCookie cookie:cookies) {
            BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue());
            c.setDomain(cookie.getDomain());
            c.setPath(cookie.getPath());
            c.setSecure(cookie.getSecure());
            c.setVersion(cookie.getVersion());
            c.setComment(cookie.getComment());
            cookieStore.addCookie(c);
        }
        context.setCookieStore(cookieStore);
        this.authenticated = true;
    }
    else {
        log.debug("Le login de l'utilisateur n'a pas pu être trouvé");
    }
}
 
Example 10
Source File: CommonToHttpServletRequest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private Cookie[] createCookies() {
  List<String> strCookies = httpHeaders.get(HttpHeaders.COOKIE);
  if (strCookies == null) {
    return new Cookie[] {};
  }

  List<Cookie> result = new ArrayList<>();
  for (String strCookie : strCookies) {
    List<HttpCookie> httpCookies = HttpCookie.parse(strCookie);
    for (HttpCookie httpCookie : httpCookies) {
      Cookie cookie = new Cookie(httpCookie.getName(), httpCookie.getValue());
      result.add(cookie);
    }
  }

  return result.toArray(new Cookie[result.size()]);
}
 
Example 11
Source File: Cookie.java    From verano-http with MIT License 6 votes vote down vote up
@Override
public final String asString() {
    final Map<String, List<String>> headers =
        new Headers.Of(this.dict).asMap();
    final String key = "Set-Cookie";
    if (headers.containsKey(key)) {
        for (final String header : headers.get(key)) {
            //@checkstyle LineLength (1 line)
            for (final HttpCookie candidate : HttpCookie.parse(header)) {
                if (candidate.getName().equals(this.name)) {
                    return candidate.getValue();
                }
            }
        }
        throw new IllegalStateException(
            String.format(
                "Cookie %s not found in Set-Cookie header.",
                this.name
            )
        );
    }
    throw new IllegalStateException("Set-Cookie header not found.");
}
 
Example 12
Source File: ResponseUtils.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
private String cookie(String cookieStringIn, String name) {
	String cookieString = cookieStringIn;
	if(cookieString==null) {
		return null;
	}

	String cookieParamName=name+"=";

	// Fix Java: rfc2965 want cookie to be separated by comma.
	// SOmehow i am receiving some semicolon separated cookies.
	// Quick Fix: First strip the preceeding cookies if not the first.
	if(!StringUtils.startsWithIgnoreCase(cookieString, cookieParamName)) {
		int indexOfIgnoreCase = StringUtils.indexOfIgnoreCase(cookieString, cookieParamName);
		cookieString = cookieString.substring(indexOfIgnoreCase);
	}
	// The proce
	List<HttpCookie> cookies = HttpCookie.parse(cookieString);
	for (HttpCookie httpCookie : cookies) {
		if(StringUtils.equalsIgnoreCase(httpCookie.getName(), name)){
			return httpCookie.getValue();
		}
	}
	return null;
}
 
Example 13
Source File: JsoScanRule.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void checkJsoInCookies(HttpMessage msg, List<HttpCookie> cookies) {
    for (HttpCookie cookie : cookies) {
        String value = cookie.getValue();
        if (!hasJsoMagicSequence(value)) {
            continue;
        }

        raiseAlert(msg, cookie.toString());
    }
}
 
Example 14
Source File: CookieAdapter.java    From SimpleProject with MIT License 5 votes vote down vote up
public CookieAdapter(HttpCookie cookie) {
	this.name = cookie.getName();
	this.value = cookie.getValue();
	this.domain = cookie.getDomain();
	this.path = cookie.getPath();
	this.secure = cookie.getSecure();
}
 
Example 15
Source File: MoverAuthenticator.java    From Mover with Apache License 2.0 5 votes vote down vote up
private String findToken(List<HttpCookie> cookies){
    for(HttpCookie cookie : cookies){
        if(cookie.getName().equalsIgnoreCase("auth_sess")){
            return cookie.getValue();
        }
    }

    return null;
}
 
Example 16
Source File: Client.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
private void checkLogin() {
    for (HttpCookie cookie : Http.Companion.getInstance().getCookieStore().getCookies()) {
        if ("4pda.User".equals(cookie.getName())) {
            UserInfoRepository.Companion.getInstance().setName(cookie.getValue());
        } else if ("4pda.K".equals(cookie.getName())) {
            m_K = cookie.getValue();
        }
    }
}
 
Example 17
Source File: KafkaWebSocketCreator.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) 
{
	boolean authGood = false;
	List<HttpCookie> cookies = request.getCookies();
	for( HttpCookie cookie : cookies )
	{
		String name = cookie.getName();
		if( name!= null && name.equals( "authToken" ))
		{
			String value = cookie.getValue();
			
			try
			{
				if( value != null && AuthToken.validateToken(configProps, value))
				{
					authGood = true;
					break;
				}
			}
			catch( Exception e )
			{
				logger.error(" Exception validating authToken:", e );
				authGood = false;
				break;
			}
			
		}
		else
		{
			continue;
		}
	}

	return new KafkaMessageSenderSocket( configProps, authGood );
}
 
Example 18
Source File: WeChatClient.java    From ChatApi-WeChat with Apache License 2.0 4 votes vote down vote up
/**
 * 初始化
 *
 * @return 初始化异常原因,为null表示正常初始化
 */
@Nullable
private String initial() {
    try {
        //通过Cookie获取重要参数
        XTools.logD(LOG_TAG, "正在获取Cookie");
        for (HttpCookie cookie : XHttpTools.EXECUTOR.getCookies()) {
            if ("wxsid".equalsIgnoreCase(cookie.getName())) {
                wxAPI.sid = cookie.getValue();
            } else if ("wxuin".equalsIgnoreCase(cookie.getName())) {
                wxAPI.uin = cookie.getValue();
            } else if ("webwx_data_ticket".equalsIgnoreCase(cookie.getName())) {
                wxAPI.dataTicket = cookie.getValue();
            }
        }

        //获取自身信息
        XTools.logD(LOG_TAG, "正在获取自身信息");
        RspInit rspInit = wxAPI.webwxinit();
        wxContacts.setMe(wxAPI.host, rspInit.User);

        //获取并保存最近联系人
        XTools.logD(LOG_TAG, "正在获取并保存最近联系人");
        loadContacts(rspInit.ChatSet, true);

        //发送初始化状态信息
        wxAPI.webwxstatusnotify(wxContacts.getMe().id, WXNotify.NOTIFY_INITED);

        //获取好友、保存的群聊、公众号列表。
        //这里获取的群没有群成员,不过也不能用fetchContact方法暴力获取群成员,因为这样数据量会很大
        XTools.logD(LOG_TAG, "正在获取好友、群、公众号列表");
        RspGetContact rspGetContact = wxAPI.webwxgetcontact();
        for (RspInit.User user : rspGetContact.MemberList) {
            wxContacts.putContact(wxAPI.host, user);
        }

        return null;
    } catch (Exception e) {
        e.printStackTrace();
        XTools.logW(LOG_TAG, String.format("初始化异常:%s", e.getMessage()));
        return INIT_EXCEPTION;
    }
}