List of usage examples for java.net HttpCookie getName
public String getName()
From source file:com.fuseim.webapp.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and * renames cookie to avoid collisions.//from ww w.j a v a 2s.c o m */ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + 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); } }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *//*w w w . ja va 2s . c om*/ 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); } }
From source file:com.yanzhenjie.nohttp.BasicRequest.java
@Override public IBasicRequest addHeader(HttpCookie cookie) { if (cookie != null) mHeaders.add(Headers.HEAD_KEY_COOKIE, cookie.getName() + "=" + cookie.getValue()); return this; }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *///from w w w .j a va 2s.c om protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); String path = servletRequest.getContextPath(); // path starts with / or // is empty string path += servletRequest.getServletPath(); // servlet path starts with / // or is empty string 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.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); } }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public String serializeLoginData() { Date loginTime = this.loginTime; if (refreshToken == null || loginTime == null) { return ""; }//from ww w .j a va 2 s .com StringBuilder builder = new StringBuilder(); builder.append("6\n"); // version builder.append(frc); builder.append("\n"); builder.append(serial); builder.append("\n"); builder.append(deviceId); builder.append("\n"); builder.append(refreshToken); builder.append("\n"); builder.append(amazonSite); builder.append("\n"); builder.append(deviceName); builder.append("\n"); builder.append(accountCustomerId); builder.append("\n"); builder.append(loginTime.getTime()); builder.append("\n"); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); builder.append(cookies.size()); builder.append("\n"); for (HttpCookie cookie : cookies) { writeValue(builder, cookie.getName()); writeValue(builder, cookie.getValue()); writeValue(builder, cookie.getComment()); writeValue(builder, cookie.getCommentURL()); writeValue(builder, cookie.getDomain()); writeValue(builder, cookie.getMaxAge()); writeValue(builder, cookie.getPath()); writeValue(builder, cookie.getPortlist()); writeValue(builder, cookie.getVersion()); writeValue(builder, cookie.getSecure()); writeValue(builder, cookie.getDiscard()); } return builder.toString(); }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public String registerConnectionAsApp(String oAutRedirectUrl) throws ConnectionException, IOException, URISyntaxException { URI oAutRedirectUri = new URI(oAutRedirectUrl); Map<String, String> queryParameters = new LinkedHashMap<String, String>(); String query = oAutRedirectUri.getQuery(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); queryParameters.put(URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()), URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name())); }/*from w ww . java 2s . co m*/ String accessToken = queryParameters.get("openid.oa2.access_token"); Map<String, String> cookieMap = new HashMap<String, String>(); List<JsonWebSiteCookie> webSiteCookies = new ArrayList<JsonWebSiteCookie>(); for (HttpCookie cookie : getSessionCookies("https://www.amazon.com")) { cookieMap.put(cookie.getName(), cookie.getValue()); webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue())); } JsonWebSiteCookie[] webSiteCookiesArray = new JsonWebSiteCookie[webSiteCookies.size()]; webSiteCookiesArray = webSiteCookies.toArray(webSiteCookiesArray); JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc, webSiteCookiesArray); String registerAppRequestJson = gson.toJson(registerAppRequest); HashMap<String, String> registerHeaders = new HashMap<String, String>(); registerHeaders.put("x-amzn-identity-auth-domain", "api.amazon.com"); String registerAppResultJson = makeRequestAndReturnString("POST", "https://api.amazon.com/auth/register", registerAppRequestJson, true, registerHeaders); JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson, JsonRegisterAppResponse.class); Response response = registerAppResponse.response; if (response == null) { throw new ConnectionException("Error: No response received from register application"); } Success success = response.success; if (success == null) { throw new ConnectionException("Error: No success received from register application"); } Tokens tokens = success.tokens; if (tokens == null) { throw new ConnectionException("Error: No tokens received from register application"); } Bearer bearer = tokens.bearer; if (bearer == null) { throw new ConnectionException("Error: No bearer received from register application"); } this.refreshToken = bearer.refresh_token; if (StringUtils.isEmpty(this.refreshToken)) { throw new ConnectionException("Error: No refresh token received"); } String usersMeResponseJson = makeRequestAndReturnString("GET", "https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null); JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class); URI uri = new URI(usersMeResponse.marketPlaceDomainName); String host = uri.getHost(); setAmazonSite(host); try { exhangeToken(); } catch (Exception e) { logout(); throw e; } String deviceName = null; Extensions extensions = success.extensions; if (extensions != null) { DeviceInfo deviceInfo = extensions.device_info; if (deviceInfo != null) { deviceName = deviceInfo.device_name; } } if (deviceName == null) { deviceName = "Unknown"; } this.deviceName = deviceName; return deviceName; }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json, boolean autoredirect, @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException { String currentUrl = url;/*from w w w .j a v a 2 s . c om*/ for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because // all response headers must be catched { int code; HttpsURLConnection connection = null; try { logger.debug("Make request to {}", url); connection = (HttpsURLConnection) new URL(currentUrl).openConnection(); connection.setRequestMethod(verb); connection.setRequestProperty("Accept-Language", "en-US"); if (customHeaders == null || !customHeaders.containsKey("User-Agent")) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); if (customHeaders != null) { for (String key : customHeaders.keySet()) { String value = customHeaders.get(key); if (StringUtils.isNotEmpty(value)) { connection.setRequestProperty(key, value); } } } connection.setInstanceFollowRedirects(false); // add cookies URI uri = connection.getURL().toURI(); if (customHeaders == null || !customHeaders.containsKey("Cookie")) { StringBuilder cookieHeaderBuilder = new StringBuilder(); for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) { if (cookieHeaderBuilder.length() > 0) { cookieHeaderBuilder.append(";"); } cookieHeaderBuilder.append(cookie.getName()); cookieHeaderBuilder.append("="); cookieHeaderBuilder.append(cookie.getValue()); if (cookie.getName().equals("csrf")) { connection.setRequestProperty("csrf", cookie.getValue()); } } if (cookieHeaderBuilder.length() > 0) { String cookies = cookieHeaderBuilder.toString(); connection.setRequestProperty("Cookie", cookies); } } if (postData != null) { logger.debug("{}: {}", verb, postData); // post data byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); int postDataLength = postDataBytes.length; connection.setFixedLengthStreamingMode(postDataLength); if (json) { connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); if (verb == "POST") { connection.setRequestProperty("Expect", "100-continue"); } connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postDataBytes); outputStream.close(); } // handle result code = connection.getResponseCode(); String location = null; // handle response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { String key = header.getKey(); if (StringUtils.isNotEmpty(key)) { if (key.equalsIgnoreCase("Set-Cookie")) { // store cookie for (String cookieHeader : header.getValue()) { if (StringUtils.isNotEmpty(cookieHeader)) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); for (HttpCookie cookie : cookies) { cookieManager.getCookieStore().add(uri, cookie); } } } } if (key.equalsIgnoreCase("Location")) { // get redirect location location = header.getValue().get(0); if (StringUtils.isNotEmpty(location)) { location = uri.resolve(location).toString(); // check for https if (location.toLowerCase().startsWith("http://")) { // always use https location = "https://" + location.substring(7); logger.debug("Redirect corrected to {}", location); } } } } } if (code == 200) { logger.debug("Call to {} succeeded", url); return connection; } if (code == 302 && location != null) { logger.debug("Redirected to {}", location); currentUrl = location; if (autoredirect) { continue; } return connection; } } catch (IOException e) { if (connection != null) { connection.disconnect(); } logger.warn("Request to url '{}' fails with unkown error", url, e); throw e; } catch (Exception e) { if (connection != null) { connection.disconnect(); } throw e; } if (code != 200) { throw new HttpException(code, verb + " url '" + url + "' failed: " + connection.getResponseMessage()); } } throw new ConnectionException("Too many redirects"); }
From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java
@Override public synchronized String getLogin() { try {/* w w w. ja v a 2 s .c o m*/ startHttpClient(); if (mUseRemoteService) { mZWaySessionId = null; mZWayRemoteSessionId = null; // Build request body String body = "act=login&login=" + mRemoteId + "/" + mUsername + "&pass=" + mPassword; logger.info("Remote login body: {}", body); logger.info("Remote path: {}", getTopLevelUrl() + "/" + REMOTE_PATH_LOGIN); Request request = mHttpClient.newRequest(getTopLevelUrl() + "/" + REMOTE_PATH_LOGIN) .method(HttpMethod.POST) .header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded") .content(new StringContentProvider(body), "application/x-www-form-urlencoded"); ContentResponse response = request.send(); // Check HTTP status code int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { String reason = response.getReason(); mCaller.httpStatusError(statusCode, reason, true); logger.debug("Communication with Z-Way server failed: {} {}", statusCode, reason); } CookieStore cookieStore = mHttpClient.getCookieStore(); List<HttpCookie> cookies = cookieStore.get(URI.create("https://find.z-wave.me/")); for (HttpCookie cookie : cookies) { if (cookie.getName().equals("ZWAYSession")) { mZWaySessionId = cookie.getValue(); } else if (cookie.getName().equals("ZBW_SESSID")) { mZWayRemoteSessionId = cookie.getValue(); } logger.info("HTTP cookie: {} - {}", cookie.getName(), cookie.getValue()); } if (mZWayRemoteSessionId != null && mZWaySessionId != null) { mCaller.getLoginResponse(mZWaySessionId); return mZWaySessionId; } else { logger.warn("Response doesn't contain required cookies"); mCaller.responseFormatError("Response doesn't contain required cookies", true); } } else { // Build request body LoginForm loginForm = new LoginForm(true, mUsername, mPassword, false, 1); Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_LOGIN) .method(HttpMethod.POST).header(HttpHeader.ACCEPT, "application/json") .header(HttpHeader.CONTENT_TYPE, "application/json") .content(new StringContentProvider(new Gson().toJson(loginForm)), "application/json"); ContentResponse response = request.send(); // Check HTTP status code int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { String reason = response.getReason(); mCaller.httpStatusError(statusCode, reason, true); logger.debug("Communication with Z-Way server failed: {} {}", statusCode, reason); } String responseBody = response.getContentAsString(); try { Gson gson = new Gson(); // Response -> String -> Json -> extract data field JsonObject responseDataAsJson = gson.fromJson(responseBody, JsonObject.class).get("data") .getAsJsonObject(); // extract data field mZWaySessionId = responseDataAsJson.get("sid").getAsString(); // extract SID field mCaller.getLoginResponse(mZWaySessionId); return mZWaySessionId; } catch (JsonParseException e) { logger.warn("Unexpected response format: {}", e.getMessage()); mCaller.responseFormatError("Unexpected response format: " + e.getMessage(), true); } } } catch (Exception e) { logger.warn("Request getLogin() failed: {}", e.getMessage()); mCaller.apiError(e.getMessage(), true); } finally { stopHttpClient(); } mZWaySessionId = null; mZWayRemoteSessionId = null; mCaller.authenticationError(); return null; }