List of usage examples for java.net HttpCookie toString
@Override
public String toString()
From source file:Main.java
public static void main(String[] args) throws Exception { CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); new URL("http://google.com").openConnection().getContent(); List<HttpCookie> cookies = cm.getCookieStore().getCookies(); for (HttpCookie cookie : cookies) { System.out.println(cookie.toString()); System.out.println();/*w w w .j a v a2s . co m*/ } }
From source file:Main.java
public static String request(String url, Map<String, String> cookies, Map<String, String> parameters) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"); if (cookies != null && !cookies.isEmpty()) { StringBuilder cookieHeader = new StringBuilder(); for (String cookie : cookies.values()) { if (cookieHeader.length() > 0) { cookieHeader.append(";"); }//from w w w.ja va 2 s . c o m cookieHeader.append(cookie); } connection.setRequestProperty("Cookie", cookieHeader.toString()); } connection.setDoInput(true); if (parameters != null && !parameters.isEmpty()) { connection.setDoOutput(true); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(parametersToWWWFormURLEncoded(parameters)); osw.flush(); osw.close(); } if (cookies != null) { for (Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) { if (headerEntry != null && headerEntry.getKey() != null && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) { for (String header : headerEntry.getValue()) { for (HttpCookie httpCookie : HttpCookie.parse(header)) { cookies.put(httpCookie.getName(), httpCookie.toString()); } } } } } Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringWriter w = new StringWriter(); char[] buffer = new char[1024]; int n = 0; while ((n = r.read(buffer)) != -1) { w.write(buffer, 0, n); } r.close(); return w.toString(); }
From source file:net.qiujuer.common.okhttp.Http.java
public static String getCookie() { CookieHandler handler = getClient().getCookieHandler(); if (handler != null && handler instanceof CookieManager) { CookieManager manager = (CookieManager) handler; CookieStore store = manager.getCookieStore(); if (store != null) { Util.log(store.toString()); try { List<HttpCookie> cookies = store.getCookies(); if (cookies.size() > 0) { String cookieStr = ""; for (HttpCookie cookie : cookies) { cookieStr += cookie.toString(); }/* ww w . j a v a2 s. c om*/ return cookieStr; } } catch (Exception e) { e.printStackTrace(); } } } return ""; }
From source file:in.rab.ordboken.CookieSerializer.java
public String saveToString() { try {//from www. j av a2 s . c om URI uri = new URI("http://" + mDomain); List<HttpCookie> cookies = mCookieStore.get(uri); JSONObject obj = new JSONObject(); JSONArray cookieStrings = new JSONArray(); for (HttpCookie cookie : cookies) { cookieStrings.put(cookie.toString()); } obj.put("cookies", cookieStrings); return obj.toString(); } catch (Exception e) { return null; } }
From source file:com.jaspersoft.android.jaspermobile.network.cookie.AppCookieStore.java
@Override public void add(URI uri, HttpCookie cookie) { mStore.add(uri, cookie); mWebViewCookieStore.add(uri.toString(), cookie.toString()); }
From source file:com.threewks.thundr.http.service.gae.HttpServiceImpl.java
private void addCookies(HttpRequestImpl request, HTTPRequest fetchRequest) { for (HttpCookie cookie : request.getCookies()) { fetchRequest.addHeader(new HTTPHeader("Cookie", cookie.toString())); }//from ww w . jav a2 s. c om }
From source file:Fetcher.Fetcher.java
/** * This method is very similar to {@code android.text.TextUtils}. Joins with * the delimeter./* w w w . j a v a 2 s. co m*/ * * @param delimmeter The character between elements. Usually is , * @param cookies The list of cookies to be join. * @return The joined string of cookies. */ private String Join(String delimmeter, List<HttpCookie> cookies) { String output = ""; for (HttpCookie cookie : cookies) { output += cookie.toString() + delimmeter; } if (output.endsWith(delimmeter)) { output = output.substring(0, output.lastIndexOf(delimmeter)); } return output; }
From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java
public OAuthToken getOAuthAccessToken(final String username, final String password) throws AuthenticationException { final OAuthToken requestToken; try {// w ww .j a v a2s. c o m 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:com.intuit.tank.okhttpclient.TankOkHttpClient.java
private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody, String method) {/*from w ww .jav a 2 s. c o m*/ String uri = null; long waitTime = 0L; try { setHeaders(request, builder, request.getHeaderInformation()); List<String> cookies = new ArrayList<String>(); if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) { for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore() .getCookies()) { cookies.add("REQUEST COOKIE: " + httpCookie.toString()); } } Request okRequest = builder.build(); uri = okRequest.uri().toString(); LOG.debug(request.getLogUtil().getLogMessage( "About to " + okRequest.method() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies, false); Response response = okHttpClient.newCall(okRequest).execute(); long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (response.code() != 203 && response.code() != 202 && response.code() != 204) { try { responseBody = response.body().bytes(); } catch (Exception e) { LOG.warn("could not get response body: " + e); } } processResponse(responseBody, startTime, endTime, request, response.message(), response.code(), response.headers()); waitTime = endTime - startTime; } catch (Exception ex) { LOG.error(request.getLogUtil().getLogMessage( "Could not do " + method + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { LOG.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:org.mozilla.testopia.transport.TestopiaXmlRpcClient.java
public TestopiaXmlRpcClient(URL url) { super();//ww w. ja va2 s .c o m 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()); } } }; } }); }