List of usage examples for java.net HttpCookie parse
public static List<HttpCookie> parse(String header)
From source file:com.handsome.frame.android.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }// w w w . ja v a 2 s . c o m map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (HandsomeApplication.getCookies() != null) { HDLog.d(TAG + "-Req-Cookie:", HandsomeApplication.getCookies().toString()); connection.addRequestProperty("Cookie", HandsomeApplication.getCookies()); } else { HDLog.d(TAG + "-Req-Cookie:", "null"); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equalsIgnoreCase("Set-Cookie")) { List<String> cookies = header.getValue(); HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>(); for (String string : cookies) { List<HttpCookie> cookie = HttpCookie.parse(string); for (HttpCookie httpCookie : cookie) { cookieMap.put(httpCookie.getName(), httpCookie); } } HandsomeApplication.setCookies(cookieMap); HDLog.d(TAG + "-Rsp-Cookie:", HandsomeApplication.getCookies().toString()); } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:com.yanzhenjie.nohttp.HttpHeaders.java
@Override public List<HttpCookie> getCookies() { List<HttpCookie> cookies = new ArrayList<>(); for (String key : keySet()) { if (key.equalsIgnoreCase(HEAD_KEY_SET_COOKIE)) { List<String> cookieValues = getValues(key); for (String cookieStr : cookieValues) { for (HttpCookie cookie : HttpCookie.parse(cookieStr)) cookies.add(cookie); }//from w w w . ja v a 2s. c o m } } return cookies; }
From source file:com.example.administrator.datarequest.ningworld.HttpHeaders.java
@Override public List<HttpCookie> getCookies() { List<HttpCookie> cookies = new ArrayList<HttpCookie>(); for (String key : keySet()) { if (key.equalsIgnoreCase(HEAD_KEY_SET_COOKIE) || key.equalsIgnoreCase(HEAD_KEY_SET_COOKIE2)) { List<String> cookieValues = getValues(key); for (String cookieStr : cookieValues) { for (HttpCookie cookie : HttpCookie.parse(cookieStr)) cookies.add(cookie); }//from w w w . j a va 2 s . c o m } } return cookies; }
From source file:ai.eve.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }//w ww .j a v a 2 s . c om if (!TextUtils.isEmpty(mSignInfo)) { map.put("SIGN", ESecurity.Encrypt(mSignInfo)); } map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (EApplication.getCookies() != null) { ELog.I("cookie", EApplication.getCookies().toString()); connection.addRequestProperty("Cookie", EApplication.getReqCookies()); } else { ELog.I("cookie", "null"); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equalsIgnoreCase("Set-Cookie")) { List<String> cookies = header.getValue(); HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>(); for (String string : cookies) { List<HttpCookie> cookie = HttpCookie.parse(string); for (HttpCookie httpCookie : cookie) { if (httpCookie.getDomain() != null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie); } else { cookieMap.put(httpCookie.getName(), httpCookie); } } } EApplication.setCookies(cookieMap); if (EApplication.getCookies() != null) { ELog.I("?cookie", EApplication.getCookies().toString()); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:com.hellofyc.base.net.http.HttpUtils.java
public HttpResponse request() { if (mDebug) { FLog.i("REQUEST URL:" + mUrlString); FLog.i("REQUEST PARAMS:" + mRequestParams.getArrayMap().toString()); FLog.i("REQUEST STRING:" + mRequestParams.getString()); }/*from w w w. j a v a 2 s. c o m*/ if (mStackTrace) { getInvokeStackTraceElement(); } HttpResponse response = new HttpResponse(); HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(mUrlString).openConnection(); configConnection(connection); response.code = connection.getResponseCode(); if (mDebug) FLog.i("===responseCode:" + response.code); if (response.code == HttpURLConnection.HTTP_OK) { String responseText = IoUtils.readStream(connection.getInputStream()); String cookie = connection.getHeaderField("Set-Cookie"); if (mDebug) FLog.i("===responseText:" + responseText); if (mDebug) FLog.i("===cookie:" + cookie); response.cookies = HttpCookie.parse(cookie); response.text = responseText; } else { response.text = connection.getResponseMessage(); } } catch (UnknownHostException e) { if (mDebug) FLog.e(e); response.code = HttpResponse.STATUS_CODE_NET; response.text = ""; return response; } catch (IOException e) { if (mDebug) FLog.e(e); response.code = HttpResponse.STATUS_CODE_UNKNOWN; response.text = "UNKNOWN"; return response; } finally { if (connection != null) { connection.disconnect(); } } return response; }
From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java
public OAuthToken getOAuthAccessToken(final String username, final String password) throws AuthenticationException { final OAuthToken requestToken; try {//from w w w .j a v a 2 s . c om requestToken = oauth.getRequestToken(OAUTH_CALLBACK_OOB); } catch (final TwitterException e) { // if (e.isCausedByNetworkIssue()) throw new AuthenticationException(e); throw new AuthenticityTokenException(e); } RestHttpResponse authorizePage = null, authorizeResult = null; try { final String oauthToken = requestToken.getOauthToken(); final HashMap<String, String> inputMap = new HashMap<>(); final RestHttpRequest.Builder authorizePageBuilder = new RestHttpRequest.Builder(); authorizePageBuilder.method(GET.METHOD); authorizePageBuilder.url(endpoint.construct("/oauth/authorize", Pair.create("oauth_token", requestToken.getOauthToken()))); final RestHttpRequest authorizePageRequest = authorizePageBuilder.build(); authorizePage = client.execute(authorizePageRequest); final String[] cookieHeaders = authorizePage.getHeaders("Set-Cookie"); readInputFromHtml(BaseTypedData.reader(authorizePage.getBody()), inputMap, INPUT_AUTHENTICITY_TOKEN, INPUT_REDIRECT_AFTER_LOGIN); final List<Pair<String, String>> params = new ArrayList<>(); params.add(Pair.create("oauth_token", oauthToken)); params.add(Pair.create(INPUT_AUTHENTICITY_TOKEN, inputMap.get(INPUT_AUTHENTICITY_TOKEN))); if (inputMap.containsKey(INPUT_REDIRECT_AFTER_LOGIN)) { params.add(Pair.create(INPUT_REDIRECT_AFTER_LOGIN, inputMap.get(INPUT_REDIRECT_AFTER_LOGIN))); } params.add(Pair.create("session[username_or_email]", username)); params.add(Pair.create("session[password]", password)); final FormTypedBody authorizationResultBody = new FormTypedBody(params); final ArrayList<Pair<String, String>> requestHeaders = new ArrayList<>(); requestHeaders.add(Pair.create("Origin", "https://twitter.com")); requestHeaders.add(Pair.create("Referer", Endpoint.constructUrl("https://twitter.com/oauth/authorize", Pair.create("oauth_token", requestToken.getOauthToken())))); final String host = parseUrlHost(endpoint.getUrl()); for (String cookieHeader : cookieHeaders) { for (HttpCookie cookie : HttpCookie.parse(cookieHeader)) { if (HttpCookie.domainMatches(cookie.getDomain(), host)) { cookie.setVersion(1); cookie.setDomain("twitter.com"); } requestHeaders.add(Pair.create("Cookie", cookie.toString())); } } final RestHttpRequest.Builder authorizeResultBuilder = new RestHttpRequest.Builder(); authorizeResultBuilder.method(POST.METHOD); authorizeResultBuilder.url(endpoint.construct("/oauth/authorize")); authorizeResultBuilder.headers(requestHeaders); authorizeResultBuilder.body(authorizationResultBody); authorizeResult = client.execute(authorizeResultBuilder.build()); final String oauthPin = readOAuthPINFromHtml(BaseTypedData.reader(authorizeResult.getBody())); if (isEmpty(oauthPin)) throw new WrongUserPassException(); return oauth.getAccessToken(requestToken, oauthPin); } catch (final IOException | NullPointerException | XmlPullParserException | TwitterException e) { throw new AuthenticationException(e); } finally { if (authorizePage != null) { IoUtils.closeSilently(authorizePage); } if (authorizeResult != null) { IoUtils.closeSilently(authorizeResult); } } }
From source file:org.mozilla.testopia.transport.TestopiaXmlRpcClient.java
public TestopiaXmlRpcClient(URL url) { super();// w ww .ja v a 2 s . c om this.url = url; this.cookies = new HashSet<HttpCookie>(); final CompositeConfiguration configuration = this.createCompositeConfiguration(); final XmlRpcClientConfig config = this.createXmlRpcClientConfiguration(configuration); ((XmlRpcClientConfigImpl) config).setServerURL(url); this.setConfig(config); // TODO: break into other classes this.setTransportFactory(new XmlRpcCommonsTransportFactory(this) { public XmlRpcTransport getTransport() { return new XmlRpcSunHttpTransport(TestopiaXmlRpcClient.this) { /* * Connection */ private URLConnection connection; /* * (non-Javadoc) * @see org.apache.xmlrpc.client.XmlRpcSunHttpTransport# * newURLConnection(java.net.URL) */ @Override protected URLConnection newURLConnection(URL pURL) throws IOException { this.connection = super.newURLConnection(pURL); return this.connection; } /** * @{inheritDoc} * * Before closing the connection, it loads the cookies in * the connection, so that they can be used later by other * methods. */ @Override protected void close() throws XmlRpcClientException { final Map<String, List<String>> headerFields = connection.getHeaderFields(); final List<String> cookieHeaders = headerFields.get("Set-Cookie"); if (cookieHeaders != null) { for (final String cookieHeader : cookieHeaders) { final String cleanCoockieHeader = cookieHeader.replace("; HttpOnly", ""); final List<HttpCookie> cookieList = HttpCookie .parse("Set-Cookie: " + cleanCoockieHeader); if (cookieList != null) { for (final HttpCookie cookie : cookieList) { cookies.add(cookie); } } } } // Now we can close it super.close(); } /** * @{inheritDoc} * * After the HTTP headers are initialized, it applies the * existing headers from this client. */ @Override protected void initHttpHeaders(XmlRpcRequest pRequest) throws XmlRpcClientException { super.initHttpHeaders(pRequest); final StringBuilder buffer = new StringBuilder(); for (final HttpCookie cookie : cookies) { if (buffer.length() > 0) { buffer.append(";"); } buffer.append(cookie.toString()); } if (buffer.length() > 0) { connection.setRequestProperty("Cookie", buffer.toString()); } } }; } }); }
From source file:com.thecorpora.qbo.androidapk.rest.RESTClient.java
/** * /*from w ww . jav a 2 s . c o m*/ * We send the user name and password parameters to the robot. * * We will get true if the access is allowed, false otherwise * * @param userName user name * @param pwd password * @param aes_string string to encrypt userName and pwd * @return true if the access is allowed, false if not. */ public HttpCookie post_login(String userName, String pwd, String aes_string) { AESCipher aes = new AESCipher(); byte[] bytesUserName = {}; byte[] bytesPwd = {}; try { bytesUserName = userName.getBytes("UTF-8"); userName = aes.encrypt(bytesUserName, aes_string); bytesPwd = pwd.getBytes("UTF-8"); pwd = aes.encrypt(bytesPwd, aes_string); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } ResponseEntity<String> response = mRest.login(userName, pwd); String cookie = response.getHeaders().getFirst("Set-Cookie"); if (cookie == null) throw new HttpClientErrorException(response.getStatusCode(), "session cookie not found"); mCookie = HttpCookie.parse(cookie).get(0); return mCookie; }
From source file:com.muk.services.security.DefaultUaaLoginService.java
@SuppressWarnings("unchecked") @Override/*from ww w . j av a2 s .com*/ public Map<String, Object> loginForClient(String username, String password, String clientId, UriComponents inUrlComponents) { final Map<String, Object> responsePayload = new HashMap<String, Object>(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer()); // login for csrf final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build(); ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers, String.class); final List<String> cookies = new ArrayList<String>(); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", username); formData.add("password", password); formData.add(CSRF, getCsrf(cookies)); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); headers.add(HttpHeaders.REFERER, loginUri.toUriString()); // login.do response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(), HttpMethod.POST, formData, headers, String.class); if (response.getStatusCode() != HttpStatus.FOUND || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) { responsePayload.put("error", "bad credentials"); return responsePayload; } removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); removeExpiredCookies(cookies); headers.remove(HttpHeaders.REFERER); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); // authorize final ResponseEntity<JsonNode> authResponse = exchangeForType( uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize") .queryParam("response_type", "code").queryParam("client_id", clientId) .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(), HttpMethod.GET, null, headers, JsonNode.class); if (authResponse.getStatusCode() == HttpStatus.OK) { removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE)); // return approval data final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>(); for (final String cookie : cookies) { parsedCookies.add(HttpCookie.parse(cookie).get(0)); } responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>()); for (final HttpCookie parsedCookie : parsedCookies) { if (!parsedCookie.getName().startsWith("Saved-Account")) { parsedCookie.setPath(inUrlComponents.getPath()); ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE)) .add(httpCookieToString(parsedCookie)); } } responsePayload.put("json", authResponse.getBody()); } else { // get auth_code from Location Header responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]); } return responsePayload; }
From source file:com.tremolosecurity.proxy.filter.PostProcess.java
protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest) throws IOException, Exception { boolean isText; HttpEntity entity = null;//from w w w. j a v a 2s.c o m try { entity = response.getEntity(); /*if (entity != null) { entity = new BufferedHttpEntity(entity); }*/ } catch (Throwable t) { throw new Exception(t); } InputStream ins = null; boolean entExists = false; if (entity == null) { resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); ins = new StringBufferInputStream(""); } else { try { ins = entity.getContent(); resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); entExists = true; } catch (IllegalStateException e) { //do nothing } } if (entExists) { org.apache.http.Header hdr = response.getFirstHeader("Content-Type"); org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding"); /*if (hdr == null) { isText = false; } else { isText = response.getFirstHeader("Content-Type").getValue().startsWith("text"); if (encoding != null ) { isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate")); } if (isText) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); resp.setLocale(response.getLocale()); } }*/ isText = false; try { resp.setCharacterEncoding(null); } catch (Throwable t) { //we're not doing anything } StringBuffer stmp = new StringBuffer(); if (response.getFirstHeader("Content-Type") != null) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); } if (response.getLocale() != null) { resp.setLocale(response.getLocale()); } org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { org.apache.http.Header header = headers[i]; if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Length")) { if (!header.getValue().equals("0")) { continue; } } else if (header.getName().equals("Transfer-Encoding")) { continue; } else if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookies = HttpCookie.parse(cookieVal); Iterator<HttpCookie> it = cookies.iterator(); while (it.hasNext()) { HttpCookie cookie = it.next(); String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { respcookie.setDomain(cookie.getDomain()); } if (cookie.hasExpired()) { respcookie.setMaxAge(0); } else { respcookie.setMaxAge((int) cookie.getMaxAge()); } respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); resp.addCookie(respcookie); } } else if (header.getName().equals("Location")) { if (holder.isOverrideHost()) { fixRedirect(req, resp, finalURL, header); } else { resp.addHeader("Location", header.getValue()); } } else { resp.addHeader(header.getName(), header.getValue()); } } curChain.setIns(ins); curChain.setText(isText); curChain.setEntity(entity); curChain.setHttpRequestBase(httpRequest); //procData(req, resp, holder, isText, entity, ins); } else { isText = false; } }