Esempio n. 1
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.start();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.url("/")));
    redirectSource.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getHostName());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.url("/").uri(), cookie);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(redirectSource.url("/"));
    RecordedRequest request = redirectSource.takeRequest();

    assertEquals("c=cookie", request.getHeader("Cookie"));

    for (String header : redirectTarget.takeRequest().getHeaders().names()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }
Esempio n. 2
0
  @Test
  public void testRfc2109Response() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "Comment=this cookie is delicious; "
                    + "Domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "Max-Age=60; "
                    + "Path=/path; "
                    + "Secure; "
                    + "Version=1"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
  }
Esempio n. 3
0
  @Test
  public void testNetscapeResponse() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
                    + "path=/path; "
                    + "domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "secure"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getComment());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertTrue(cookie.getMaxAge() > 100000000000L);
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
    assertEquals(0, cookie.getVersion());
  }
Esempio n. 4
0
  @Test
  public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.play();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = new HttpCookie("a", "android");
    cookieA.setDomain(server.getCookieDomain());
    cookieA.setPath("/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieA);
    HttpCookie cookieB = new HttpCookie("b", "banana");
    cookieB.setDomain(server.getCookieDomain());
    cookieB.setPath("/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieB);
    CookieHandler.setDefault(cookieManager);

    get(server, "/");
    RecordedRequest request = server.takeRequest();

    List<String> receivedHeaders = request.getHeaders();
    assertContains(
        receivedHeaders,
        "Cookie: $Version=\"1\"; "
            + "a=\"android\";$Path=\"/\";$Domain=\""
            + server.getCookieDomain()
            + "\"; "
            + "b=\"banana\";$Path=\"/\";$Domain=\""
            + server.getCookieDomain()
            + "\"");
  }
Esempio n. 5
0
  @Test
  public void testNetscapeResponse() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    CookieHandler.setDefault(cookieManager);
    MockWebServer server = new MockWebServer();
    server.play();

    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
                    + "path=/path; "
                    + "domain="
                    + server.getCookieDomain()
                    + "; "
                    + "secure"));
    get(server, "/path/foo");

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getComment());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertTrue(server.getCookieDomain().equalsIgnoreCase(cookie.getDomain()));
    assertTrue(cookie.getMaxAge() > 100000000000L);
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
    assertEquals(0, cookie.getVersion());
  }
Esempio n. 6
0
  public RestClient(Context context) {
    Gson gson =
        new GsonBuilder()
            .setDateFormat(context.getString(R.string.server_date_time_format))
            .create();

    OkHttpClient client = new OkHttpClient(); // create OKHTTPClient

    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(60, TimeUnit.SECONDS);

    client.interceptors().add(((Application) context).getAuthInterceptor());

    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager); // finally set the cookie handler on client

    OkClient serviceClient = new OkClient(client);

    RestAdapter restAdapter =
        new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(context.getString(R.string.server_url))
            .setConverter(new GsonConverter(gson))
            .setClient(serviceClient)
            .build();

    RestAdapter restAdapterOCR =
        new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(context.getString(R.string.server_url_ocr))
            .setConverter(new GsonConverter(gson))
            .setClient(serviceClient)
            .build();

    authenticationService = restAdapter.create(AuthenticationService.class);
    linkedInService = restAdapter.create(LinkedInService.class);
    addressService = restAdapter.create(AddressService.class);
    aadhaarService = restAdapter.create(AadhaarService.class);
    primaryBankService = restAdapter.create(PrimaryBankService.class);
    panCardService = restAdapter.create(PanCardService.class);
    businessCardService = restAdapter.create(BusinessCardService.class);
    incomeService = restAdapter.create(IncomeService.class);
    userHistoryService = restAdapter.create(UserHistoryService.class);
    facebookService = restAdapter.create(FacebookService.class);
    panCardServiceOCR = restAdapterOCR.create(PanCardService.class);
    avtarService = restAdapter.create(AvtarService.class);
    referenceService = restAdapter.create(ReferenceService.class);
    bankSnapService = restAdapter.create(BankSnapService.class);
    emiService = restAdapter.create(EMIService.class);

    eStatementService = restAdapter.create(EStatementService.class);
    netBankingService = restAdapter.create(NetBankingService.class);
    transUnionService = restAdapter.create(GetCreditLineBankService.class);
    getUserLoanService = restAdapter.create(GetUserLoanService.class);
    loanDetailService = restAdapter.create(LoanDetailService.class);
    transactionsService = restAdapter.create(TransactionsService.class);
    profileService = restAdapter.create(ProfileService.class);
    instance = this;
  }
Esempio n. 7
0
  @Test
  public void testRfc2109Response() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    CookieHandler.setDefault(cookieManager);
    MockWebServer server = new MockWebServer();
    server.play();

    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "Comment=this cookie is delicious; "
                    + "Domain="
                    + server.getCookieDomain()
                    + "; "
                    + "Max-Age=60; "
                    + "Path=/path; "
                    + "Secure; "
                    + "Version=1"));
    get(server, "/path/foo");

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals("this cookie is delicious", cookie.getComment());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertTrue(server.getCookieDomain().equalsIgnoreCase(cookie.getDomain()));
    assertEquals(60, cookie.getMaxAge());
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
    assertEquals(1, cookie.getVersion());
  }
 /**
  * To set the cookie policy of this cookie manager.
  *
  * <p>A instance of <tt>CookieManager</tt> will have cookie policy ACCEPT_ORIGINAL_SERVER by
  * default. Users always can call this method to set another cookie policy.
  *
  * @param cookiePolicy the cookie policy. Can be <tt>null</tt>, which has no effects on current
  *     cookie policy.
  */
 @Override
 public void setCookiePolicy(final CookiePolicy cookiePolicy) {
   if (cookiePolicy != null) {
     policyCallback = cookiePolicy;
     super.setCookiePolicy(cookiePolicy);
   }
 }
Esempio n. 9
0
  public static String call(String address)
      throws HttpClientException, IOException, URISyntaxException {
    URL url = new URL(address);
    URI uri = new URI(address);
    CookieManager cookieManager = (CookieManager) CookieHandler.getDefault();

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setConnectTimeout(10000);
    urlConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);
    if (cookieManager != null && cookieManager.getCookieStore().getCookies().size() > 0) {
      urlConnection.setRequestProperty(
          "Cookie", TextUtils.join("; ", cookieManager.getCookieStore().get(uri)));
    }
    urlConnection.connect();

    int code = urlConnection.getResponseCode();

    // Read the input stream into a String
    InputStream inputStream = urlConnection.getInputStream();
    StringBuilder builder = new StringBuilder();
    if (inputStream == null) {
      // Nothing to do.
      return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
    }

    if (builder.length() == 0) {
      // Stream was empty.  No point in parsing.
      return null;
    }

    String result = builder.toString();

    if (code != 200) {
      throw new HttpClientException(result, code);
    }

    return result;
  }
Esempio n. 10
0
 public void updateCookies(URL url, Map<String, List<String>> responseHeaders) {
   try {
     cookieManager.put(url.toURI(), responseHeaders);
   } catch (IOException e) {
     throw new HttpToolsException("Error on cookie storing: " + url, e);
   } catch (URISyntaxException e) {
     throw new HttpToolsException("Url syntax error on cookie storing: " + url, e);
   }
 }
Esempio n. 11
0
 public Map<String, List<String>> getCookies(URL url) {
   try {
     return cookieManager.get(url.toURI(), new HashMap<String, List<String>>());
   } catch (IOException e) {
     throw new HttpToolsException("Error on cookie storing: " + url, e);
   } catch (URISyntaxException e) {
     throw new HttpToolsException("Url syntax error on cookie storing: " + url, e);
   }
 }
Esempio n. 12
0
  @Test
  public void testQuotedAttributeValues() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    CookieHandler.setDefault(cookieManager);
    MockWebServer server = new MockWebServer();
    server.play();

    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie2: a=\"android\"; "
                    + "Comment=\"this cookie is delicious\"; "
                    + "CommentURL=\"http://google.com/\"; "
                    + "Discard; "
                    + "Domain=\""
                    + server.getCookieDomain()
                    + "\"; "
                    + "Max-Age=\"60\"; "
                    + "Path=\"/path\"; "
                    + "Port=\"80,443,"
                    + server.getPort()
                    + "\"; "
                    + "Secure; "
                    + "Version=\"1\""));
    get(server, "/path/foo");

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals("this cookie is delicious", cookie.getComment());
    assertEquals("http://google.com/", cookie.getCommentURL());
    assertEquals(true, cookie.getDiscard());
    assertTrue(server.getCookieDomain().equalsIgnoreCase(cookie.getDomain()));
    assertEquals(60, cookie.getMaxAge());
    assertEquals("/path", cookie.getPath());
    assertEquals("80,443," + server.getPort(), cookie.getPortlist());
    assertEquals(true, cookie.getSecure());
    assertEquals(1, cookie.getVersion());
  }
Esempio n. 13
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.play();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.getUrl("/")));
    redirectSource.play();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getCookieDomain());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.getUrl("/").toURI(), cookie);
    CookieHandler.setDefault(cookieManager);

    get(redirectSource, "/");
    RecordedRequest request = redirectSource.takeRequest();

    assertContains(
        request.getHeaders(),
        "Cookie: $Version=\"1\"; "
            + "c=\"cookie\";$Path=\"/\";$Domain=\""
            + redirectSource.getCookieDomain()
            + "\";$Port=\""
            + portList
            + "\"");

    for (String header : redirectTarget.takeRequest().getHeaders()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }
Esempio n. 14
0
  @Test
  public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = new HttpCookie("a", "android");
    cookieA.setDomain(server.getHostName());
    cookieA.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieA);
    HttpCookie cookieB = new HttpCookie("b", "banana");
    cookieB.setDomain(server.getHostName());
    cookieB.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieB);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(server.url("/"));
    RecordedRequest request = server.takeRequest();

    assertEquals("a=android; b=banana", request.getHeader("Cookie"));
  }
  public DVWebApiClient(
      String serviceUrl, String sessionId, boolean useSystemProxies, int connectTimeoutInSeconds) {
    try {
      this.serviceUrl = serviceUrl;
      this.sessionId = sessionId;
      this.connectTimeoutInSeconds = connectTimeoutInSeconds;

      if (useSystemProxies) {
        //                System.setProperty("java.net.useSystemProxies", "true");
      }

      // remove the java applet/javaws CookieManager because it interferes with the JSESSIONID
      // cookie we try to set which came from the browser
      CookieManager.setDefault(null);

      Map<String, String> cookies = new HashMap();
      // if session does not exist create it and set it
      if (sessionId == null || sessionId.length() == 0) {
        WebApi tempProxy =
            (WebApi)
                MyProxyFactory.getProxy(
                    WebApi.class,
                    new URL(serviceUrl),
                    this.getClass().getClassLoader(),
                    connectTimeoutInSeconds * 1000,
                    true,
                    cookies,
                    xForwardedFor);
        sessionId = tempProxy.getWebSessionId();
      }
      cookies.put("JSESSIONID", sessionId);
      webApiProxy =
          (WebApi)
              MyProxyFactory.getProxy(
                  WebApi.class,
                  new URL(serviceUrl),
                  this.getClass().getClassLoader(),
                  connectTimeoutInSeconds * 1000,
                  true,
                  cookies,
                  xForwardedFor);
    } catch (Throwable ex) {
      throw new RuntimeException(ex);
    }
  }
Esempio n. 16
0
  public void loadState(Activity a) {
    SharedPreferences prefs = a.getSharedPreferences("cookies", 0);
    String cookie = prefs.getString("RevTK", "no value");

    Log.v(DEBUG_TAG, "loaded RevTK cookie: " + cookie);

    HttpCookie revTKCookie = new HttpCookie("RevTK", cookie);
    revTKCookie.setVersion(0);
    revTKCookie.setDomain("kanji.koohii.com");

    try {
      if (!(cookie.equals("no value") || revTKCookie.hasExpired())) {
        cm.getCookieStore().add(new URI("http://kanji.koohii.com/"), revTKCookie);
        loggedIn = true;
      }
    } catch (URISyntaxException e) { // should not happen
      e.printStackTrace();
    }
  }
Esempio n. 17
0
  public void saveState(Activity a) {
    Log.v(DEBUG_TAG, "saveState() requested");

    if (!loggedIn) {
      return;
    }

    Log.v(DEBUG_TAG, "saving state");
    SharedPreferences prefs = a.getSharedPreferences("cookies", 0);
    SharedPreferences.Editor editor = prefs.edit();

    for (HttpCookie cookie : cm.getCookieStore().getCookies()) {
      if (cookie.getName().equals("RevTK")) {
        Log.v(DEBUG_TAG, "put RevTK cookie");
        editor.putString(cookie.getName(), cookie.getValue());
        break;
      }
    }

    editor.apply();
  }
Esempio n. 18
0
 /** @see http://blogs.sun.com/CoreJavaTechTips/entry/cookie_handling_in_java_se */
 public static void enableCookieMgmt() {
   CookieManager manager = new CookieManager();
   manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
   CookieHandler.setDefault(manager);
 }
Esempio n. 19
0
 static {
   defaultCookieManager = new CookieManager();
   defaultCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
 }
Esempio n. 20
0
  /**
   * invoke via Loader
   *
   * @throws IOException
   */
  @Override
  @TargetApi(Build.VERSION_CODES.KITKAT)
  public void sendRequest() throws IOException {
    isLoading = false;

    URL url = new URL(queryUrl);
    { // init connection
      Proxy proxy = params.getProxy();
      if (proxy != null) {
        connection = (HttpURLConnection) url.openConnection(proxy);
      } else {
        connection = (HttpURLConnection) url.openConnection();
      }
      connection.setInstanceFollowRedirects(true);
      connection.setReadTimeout(params.getConnectTimeout());
      connection.setConnectTimeout(params.getConnectTimeout());
      if (connection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(params.getSslSocketFactory());
      }
    }

    { // add headers
      try {
        Map<String, List<String>> singleMap =
            COOKIE_MANAGER.get(url.toURI(), new HashMap<String, List<String>>(0));
        List<String> cookies = singleMap.get("Cookie");
        if (cookies != null) {
          connection.setRequestProperty("Cookie", TextUtils.join(";", cookies));
        }
      } catch (Throwable ex) {
        LogUtil.e(ex.getMessage(), ex);
      }

      HashMap<String, String> headers = params.getHeaders();
      if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
          String name = entry.getKey();
          String value = entry.getValue();
          if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
            connection.setRequestProperty(name, value);
          }
        }
      }
    }

    { // write body
      HttpMethod method = params.getMethod();
      connection.setRequestMethod(method.toString());
      if (HttpMethod.permitsRequestBody(method)) {
        RequestBody body = params.getRequestBody();
        if (body != null) {
          if (body instanceof ProgressBody) {
            ((ProgressBody) body).setProgressHandler(progressHandler);
          }
          String contentType = body.getContentType();
          if (!TextUtils.isEmpty(contentType)) {
            connection.setRequestProperty("Content-Type", contentType);
          }
          long contentLength = body.getContentLength();
          if (contentLength < 0) {
            connection.setChunkedStreamingMode(256 * 1024);
          } else {
            if (contentLength < Integer.MAX_VALUE) {
              connection.setFixedLengthStreamingMode((int) contentLength);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
              connection.setFixedLengthStreamingMode(contentLength);
            } else {
              connection.setChunkedStreamingMode(256 * 1024);
            }
          }
          connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
          connection.setDoOutput(true);
          body.writeTo(connection.getOutputStream());
        }
      }
    }

    LogUtil.d(queryUrl);
    int code = connection.getResponseCode();
    if (code >= 300) {
      HttpException httpException = new HttpException(code, connection.getResponseMessage());
      try {
        httpException.setResult(IOUtil.readStr(connection.getInputStream(), params.getCharset()));
      } catch (Throwable ignored) {
      }
      throw httpException;
    }

    { // save cookies
      try {
        Map<String, List<String>> headers = connection.getHeaderFields();
        if (headers != null) {
          COOKIE_MANAGER.put(url.toURI(), headers);
        }
      } catch (Throwable ex) {
        LogUtil.e(ex.getMessage(), ex);
      }
    }

    isLoading = true;
  }