public static String get(String requestUrl, CookieManager cookies) throws Exception { URL url = new URL(urlEncode(requestUrl)); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); if (cookies != null) applyCookies(connection); connection.setConnectTimeout(8 * 1000); connection.setRequestProperty("User-Agent", FrameworkConstants.FRAMEWORK_NAME); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String text; StringBuilder result = new StringBuilder(); while ((text = in.readLine()) != null) result.append(text); in.close(); storeCookies(connection); return result.toString(); }
@Test public void testSendingCookiesFromStore() throws Exception { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse()); server.start(); HttpUrl serverUrl = urlWithIpAddress(server, "/"); CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER); HttpCookie cookieA = new HttpCookie("a", "android"); cookieA.setDomain(serverUrl.host()); cookieA.setPath("/"); cookieManager.getCookieStore().add(serverUrl.uri(), cookieA); HttpCookie cookieB = new HttpCookie("b", "banana"); cookieB.setDomain(serverUrl.host()); cookieB.setPath("/"); cookieManager.getCookieStore().add(serverUrl.uri(), cookieB); client = client.newBuilder() .cookieJar(new JavaNetCookieJar(cookieManager)) .build(); get(serverUrl); RecordedRequest request = server.takeRequest(); assertEquals("a=android; b=banana", request.getHeader("Cookie")); }
@Test public void receiveAndSendMultipleCookies() throws Exception { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse() .addHeader("Set-Cookie", "a=android") .addHeader("Set-Cookie", "b=banana")); server.enqueue(new MockResponse()); server.start(); CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER); client = client.newBuilder() .cookieJar(new JavaNetCookieJar(cookieManager)) .build(); get(urlWithIpAddress(server, "/")); RecordedRequest request1 = server.takeRequest(); assertNull(request1.getHeader("Cookie")); get(urlWithIpAddress(server, "/")); RecordedRequest request2 = server.takeRequest(); assertEquals("a=android; b=banana", request2.getHeader("Cookie")); }
@Test public void testCookiesSentIgnoresCase() throws Exception { client = client.newBuilder() .cookieJar(new JavaNetCookieJar(new CookieManager() { @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> result = new LinkedHashMap<>(); result.put("COOKIE", Collections.singletonList("Bar=bar")); result.put("cooKIE2", Collections.singletonList("Baz=baz")); return result; } })) .build(); MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse()); server.start(); get(server.url("/")); RecordedRequest request = server.takeRequest(); assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie")); assertNull(request.getHeader("Cookie2")); assertNull(request.getHeader("Quux")); }
private static OkHttpClientImpl _getClient(CookieHandler cookieHandler) { OkHttpClientImpl okHttpClient = new OkHttpClientImpl(); //okHttpClient.setConnectTimeout(SET_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); //okHttpClient.setReadTimeout(SET_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); //okHttpClient.setWriteTimeout(SET_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); if (cookieHandler == null) { CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_NONE); okHttpClient._setCookieHandler(cookieManager); } else { okHttpClient._setCookieHandler(cookieHandler); } return okHttpClient; }
void doClientSide() throws Exception { // Wait for server to get started. while (!serverReady) { Thread.sleep(50); } HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; }}); URL url = new URL("https://localhost:" + serverPort +"/"); // Run without a CookieHandler first InputStream in = url.openConnection().getInputStream(); while (in.read() != -1); // read response body so connection can be reused // Set a CookeHandler and retest using the HttpClient from the KAC CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(manager); in = url.openConnection().getInputStream(); while (in.read() != -1); if (manager.getCookieStore().getCookies().isEmpty()) { throw new RuntimeException("Failed: No cookies in the cookie Handler."); } }
CookieHttpClientTest() throws Exception { /* start the server */ ss = new ServerSocket(0); (new Thread(this)).start(); URL url = new URL("http://localhost:" + ss.getLocalPort() +"/"); // Run without a CookieHandler first InputStream in = url.openConnection().getInputStream(); while (in.read() != -1); // read response body so connection can be reused // Set a CookeHandler and retest using the HttpClient from the KAC CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(manager); in = url.openConnection().getInputStream(); while (in.read() != -1); if (manager.getCookieStore().getCookies().isEmpty()) { throw new RuntimeException("Failed: No cookies in the cookie Handler."); } }
public static String post(String requestUrl, String payload, CookieManager cookies) throws Exception { URL url = new URL(urlEncode(requestUrl)); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); if (cookies != null) applyCookies(connection); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(payload); writer.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder jsonString = new StringBuilder(); String line; while ((line = br.readLine()) != null) jsonString.append(line); br.close(); connection.disconnect(); storeCookies(connection); return jsonString.toString(); }
@Override public HttpRequestImpl response(Response r) throws IOException { HttpHeaders hdrs = r.headers(); HttpRequestImpl request = r.request(); Exchange<?> e = r.exchange; Log.logTrace("Response: processing cookies for {0}", request.uri()); Optional<CookieManager> cookieManOpt = e.client().cookieManager(); if (cookieManOpt.isPresent()) { CookieManager cookieMan = cookieManOpt.get(); Log.logTrace("Response: parsing cookies from {0}", hdrs.map()); cookieMan.put(request.uri(), hdrs.map()); } else { Log.logTrace("Response: No cookie manager found for {0}", request.uri()); } return null; }
private void initCookies() { CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); if (cookieManager.getCookieStore().getCookies().size() == 0) { try { String url = SharedPreferencesEditor.getInstance().getString( Constants.PREFS_URL_SHORTCUT); URI uri = new URI(url); HttpCookie cookie = new HttpCookie(Constants.COOKIE_AUTH_NAME, SharedPreferencesEditor.getInstance().getString( Constants.PREFS_AUTH)); cookie.setDomain(uri.getHost()); cookie.setPath(Constants.COOKIE_BASE_PATH); cookie.setVersion(0); cookie.setMaxAge((new Date()).getTime() + Constants.COOKIE_LIFETIME_YEAR); cookieManager.getCookieStore().add(uri, cookie); } catch (URISyntaxException e) { e.printStackTrace(); } } }
/** * <p>It isn't possible to follow * <a href="https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html">Oracle Accessing Cookies Tutorial</a> * via default {@link CookieManager} with {@link java.net.InMemoryCookieStore} under the hood. * * <p>{@link CookieManager} is the implementation of <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>. * But the website needs to implement <a href="http://www.ietf.org/rfc/rfc6265.txt">RFC 6265</a>. * * <p>RFC 2965: "x.y.com domain-matches .Y.com but not Y.com."<br/> * RFC 6265: "The domain string is a suffix of the string. The last character of the string that is not included in the domain string is a "." character." <br/> * Take a look at <a href="https://github.com/square/okhttp/issues/991">OkHttp #991</a>. * * <p>So, private {@link com.sun.webkit.network.CookieManager} is implementing RFC 6265, that's why it's using. * * @return session id if it exists or {@code null} */ @SneakyThrows private String fetchSessionId() { Map<String, List<String>> headers = CookieManager.getDefault().get(COOKIE_DOMAIN_URI, new HashMap<>()); List<String> values = headers.getOrDefault("Cookie", new ArrayList<>()); if (values.isEmpty()) { return null; } String headerValue = values.get(0); String[] cookieEntries = headerValue.split(";"); for (String cookieEntry : cookieEntries) { String[] cookieParts = cookieEntry.split("="); if ("remixsid".equals(cookieParts[0].trim())) { return cookieParts[1].trim(); } } return null; }
Call post(Callback callback) throws IOException { OkHttpClient client = getUnsafeOkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); RequestBody requestBody = new FormEncodingBuilder() .add("user_id", NetId) .add("user_password", password) .build(); Request request = new Request.Builder() .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
public LoginService() { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); mPersistentCookieStore = new PersistentCookieStore(MyApplication.getContextObject()); mClient = new OkHttpClient.Builder() .cookieJar(new CustomCookieJar(new CookieManager(mPersistentCookieStore, CookiePolicy.ACCEPT_ALL))) .readTimeout(12, TimeUnit.SECONDS) .addInterceptor(htmlInterceptor) .addInterceptor(loggingInterceptor) .build(); mGson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .serializeNulls() .create(); }
@Test public void testCookiesSentIgnoresCase() throws Exception { client = client.newBuilder() .cookieJar(new JavaNetCookieJar(new CookieManager() { @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> result = new HashMap<>(); result.put("COOKIE", Collections.singletonList("Bar=bar")); result.put("cooKIE2", Collections.singletonList("Baz=baz")); return result; } })) .build(); MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse()); server.start(); get(server.url("/")); RecordedRequest request = server.takeRequest(); assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie")); assertNull(request.getHeader("Cookie2")); assertNull(request.getHeader("Quux")); }
public void tstGetPost() throws Exception { String urlSource = "http://localhost:8080/beige-accounting-web/secure/main.jsp"; String urlBase = urlSource.substring(0, urlSource.indexOf("secure") - 1); assertEquals("http://localhost:8080/beige-accounting-web", urlBase); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cookieManager); URL url = new URL(urlSource); Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", "admin"); params.put("userPass", "admin"); params.put("authMethod", "form"); params.put("urlBase", urlBase); params.put("authUrl", urlBase + "/secure/j_security_check"); params.put("authUserName", "j_username"); params.put("authUserPass", "j_password"); params.put("urlSource", urlSource); tstAuthGet(url, params, cookieManager); //either Get or Post for test allowed urlSource = "http://localhost:8080/beige-accounting-web/secure/sendEntities"; params.put("urlSource", urlSource); //url = new URL(urlSource); //tstAuthPost(url, params, cookieManager); }
private OkHttpClientManager() { mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); mGson = new Gson(); //just for test if (false) { mOkHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } }
private OkHttpUtils() { mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); if (true) { mOkHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } }
private static void setup() { baseUrlManager = new BaseUrlManager(UrlConstants.SKS1_BASE); okHttpClient = new OkHttpClient(); cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); okHttpClient.setCookieHandler(cookieManager); okHttpClient.setConnectTimeout(5, TimeUnit.SECONDS); okHttpClient.setReadTimeout(5, TimeUnit.SECONDS); okHttpClient.setWriteTimeout(5, TimeUnit.SECONDS); okHttpClient.interceptors().add(new HandlerResponseInterceptor()); retrofit = new Retrofit.Builder() .baseUrl(baseUrlManager) .client(okHttpClient) .addConverterFactory(new DocumentConverterFactory()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); service = retrofit.create(ConnectionService.class); }
public static void apiInit() { try { CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); OkHttpClient okHttpClient = new OkHttpClient.Builder() .cookieJar(new JavaNetCookieJar(cookieManager)) .build(); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build(); // Service setup apiService = retrofit.create(CodenvyApiService.class); } catch (Exception e) { e.printStackTrace(); } }
public CoreServices(Context context) { this.context = context; // Storage sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); cookieStore = new PersistentCookieStore(context); // General userManager = new UserManager(sharedPrefs); errorHandler = new ErrorHandler(context); localBroadcastManager = LocalBroadcastManager.getInstance(context); // Network firebaseRef = new Firebase(Constants.FIREBASE_URL); okHttpClient = new OkHttpClient(); okHttpClient.setCookieHandler(new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL)); // Tasks codementorTasks = new CodementorTasks(okHttpClient); firebaseTasks = new FirebaseTasks(firebaseRef, codementorTasks, userManager); }
OkHttpClient provideHttpClient() { OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(30, TimeUnit.SECONDS); builder.addInterceptor(new KinopoiskRequestInterceptor()); // Log http requests on debug if (BuildConfig.DEBUG) { //logging interceptor should be last interceptor in chain HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(loggingInterceptor); } CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); builder.cookieJar(new JavaNetCookieJar(cookieManager)); return builder.build(); }
private OkNet() { OkHttpClient.Builder builder = client.newBuilder(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_NONE); builder.cookieJar(new JavaNetCookieJar(cookieManager)); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); builder.connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS); client = builder.build(); }
public static void main(String[] args) { AppVars.setAppVars(); Preferences.load(); if (Preferences.useSystemLookAndFeel()) { useSystemLookAndFeel(true); } CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); if (Preferences.useUserProxy()) { ComicUtil.setProxy(Preferences.getProxyAddress(), Preferences.getProxyPort(), Preferences.getProxyUsername(), Preferences.getProxyEncryptedPassword()); } ComicUtil.getNewestComic(); EventQueue.invokeLater(() -> { MainFrame frame = new MainFrame("XKCDownload"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setLocationRelativeTo(null); }); }
/** * If a ref tag cookie has been stored for this project this returns the ref tag embedded in the cookie. If a * cookie has not yet been set it returns `null`. */ public static @Nullable RefTag storedCookieRefTagForProject(final @NonNull Project project, final @NonNull CookieManager cookieManager, final @NonNull SharedPreferences sharedPreferences) { final HttpCookie cookie = findRefTagCookieForProject(project, cookieManager, sharedPreferences); if (cookie == null) { return null; } final String[] components = cookie.getValue() .split(COOKIE_VALUE_SEPARATOR); if (components.length > 0) { return RefTag.from(components[0]); } return null; }
/** * Finds the ref tag cookie associated with a project. Returns `null` if no cookie has yet been set. */ protected static @Nullable HttpCookie findRefTagCookieForProject(final @NonNull Project project, final @NonNull CookieManager cookieManager, final @NonNull SharedPreferences sharedPreferences) { final String cookieName = cookieNameForProject(project); // First try finding the cookie in the cookie store final CookieStore cookieStore = cookieManager.getCookieStore(); for (final HttpCookie cookie : cookieStore.getCookies()) { if (cookieName.equals(cookie.getName())) { return cookie; } } // If we can't find it in the cookie store let's look in shared prefs final String cookieValue = sharedPreferences.getString(cookieName, null); if (cookieValue != null) { return buildCookieWithValueAndProject(cookieValue, project); } return null; }
public static void initCookieManager() { CookieHandler cookieHandler = CookieHandler.getDefault(); if (cookieHandler == null) { // CookieStore cookieStore = CookieStoreHolder.initInMemoryCookieStore(); // CookieManager cm = new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL); CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); } // else { // CookieStoreHolder.initInMemoryCookieStore(); // } }
/** * Creates an instance of the builder with a base URL and 2 custom builders. * * @param httpClientBuilder the builder to build an {@link OkHttpClient}. * @param retrofitBuilder the builder to build a {@link Retrofit}. */ public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) { if (httpClientBuilder == null) { throw new IllegalArgumentException("httpClientBuilder == null"); } if (retrofitBuilder == null) { throw new IllegalArgumentException("retrofitBuilder == null"); } CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); customHeadersInterceptor = new CustomHeadersInterceptor(); // Set up OkHttp client this.httpClientBuilder = httpClientBuilder .cookieJar(new JavaNetCookieJar(cookieManager)) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(new RequestIdHeaderInterceptor()) .addInterceptor(new BaseUrlHandler()); this.retrofitBuilder = retrofitBuilder; this.loggingInterceptor = new LoggingInterceptor(LogLevel.NONE); }
private HttpManager() { this.mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); final int sdk = Build.VERSION.SDK_INT; if (sdk >= 23) { GsonBuilder gsonBuilder = new GsonBuilder() .excludeFieldsWithModifiers( Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC); mGson = gsonBuilder.create(); } else { mGson = new Gson(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); android.webkit.CookieManager.getInstance().setAcceptCookie(true); CookieManager cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cookieManager); new APITask(new APICallback() { @Override public void r(String result) { if (result.length() != 0) { Intent queueList = new Intent(MainActivity.this, QueueListActivity.class); startActivity(queueList); } else { setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } } }).execute("method", "userData"); }