org.apache.http.cookie.Cookie Java Examples

The following examples show how to use org.apache.http.cookie.Cookie. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebFragment.java    From BigApp_Discuz_Android with Apache License 2.0 8 votes vote down vote up
@Override
    public void setCookieFromCookieStore(Context context, String url, List<Cookie> cks) {
        CookieUtils.syncCookie(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);

        if (!ListUtils.isNullOrContainEmpty(cks)) {
            for (int i = 0; i < cks.size(); i++) {
                Cookie cookie = cks.get(i);
                String cookieStr = cookie.getName() + "=" + cookie.getValue() + ";"
                        + "expiry=" + cookie.getExpiryDate() + ";"
                        + "domain=" + cookie.getDomain() + ";"
                        + "path=/";
//                ZogUtils.printError(WebFragment.class, "set cookie string:" + cookieStr);
                cookieManager.setCookie(url, cookieStr);//cookieStr是在HttpClient中获得的cookie

            }
        }
    }
 
Example #2
Source File: MyCookieDBManager.java    From Huochexing12306 with Apache License 2.0 6 votes vote down vote up
public void saveCookie(Cookie cookie) {
	L.d("saveCookie:" + cookie);
	if (cookie == null) {
		return;
	}
	db.delete(TABLE_NAME, Column.NAME + " = ? ",
			new String[] { cookie.getName() });
	ContentValues values = new ContentValues();
	values.put(Column.VALUE, cookie.getValue());
	values.put(Column.NAME, cookie.getName());
	values.put(Column.COMMENT, cookie.getComment());
	values.put(Column.DOMAIN, cookie.getDomain());
	if (cookie.getExpiryDate() != null) {
		values.put(Column.EXPIRY_DATE, cookie.getExpiryDate().getTime());
	}
	values.put(Column.PATH, cookie.getPath());
	values.put(Column.SECURE, cookie.isSecure() ? 1 : 0);
	values.put(Column.VERSION, cookie.getVersion());

	db.insert(TABLE_NAME, null, values);
}
 
Example #3
Source File: PersistentCookieStore.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}
 
Example #4
Source File: HC4ExchangeFormAuthenticator.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Look for session cookies.
 *
 * @return true if session cookies are available
 */
protected boolean isAuthenticated(ResponseWrapper getRequest) {
    boolean authenticated = false;
    if (getRequest.getStatusCode() == HttpStatus.SC_OK
            && "/ews/services.wsdl".equalsIgnoreCase(getRequest.getURI().getPath())) {
        // direct EWS access returned wsdl
        authenticated = true;
    } else {
        // check cookies
        for (Cookie cookie : httpClientAdapter.getCookies()) {
            // Exchange 2003 cookies
            if (cookie.getName().startsWith("cadata") || "sessionid".equals(cookie.getName())
                    // Exchange 2007 cookie
                    || "UserContext".equals(cookie.getName())
            ) {
                authenticated = true;
                break;
            }
        }
    }
    return authenticated;
}
 
Example #5
Source File: PersistentCookieStore.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}
 
Example #6
Source File: PersistentCookieStore.java    From android-project-wo2b with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a persistent cookie store.
 *
 * @param context Context to attach cookie store to
 */
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
 
Example #7
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a string with all the cookies.
 * @param httpContext the context.
 * @param separator the separator string between cookies.
 * @return a new string with all the cookies.
 */
public static String getAllCookies(HttpContext httpContext, String separator){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    String cookieValue;
    StringBuilder result = new StringBuilder();
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        cookieValue = cookies.get(i).getValue();
        result
            .append(cookieName)
            .append("=")
            .append(cookieValue)
            .append(separator);
    }
    return result.toString();
}
 
Example #8
Source File: CookieConverterTest.java    From storm-crawler with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotExpiredCookie() {
    String[] cookiesStrings = new String[1];
    String dummyCookieString = buildCookieString(dummyCookieHeader,
            dummyCookieValue, null, "Tue, 11 Apr 2117 07:13:39 -0000",
            null, null);
    cookiesStrings[0] = dummyCookieString;
    List<Cookie> result = CookieConverter.getCookies(cookiesStrings,
            getUrl(unsecuredUrl));
    Assert.assertEquals("Should have 1 cookie", 1, result.size());
    Assert.assertEquals("Cookie header should be as defined",
            dummyCookieHeader, result.get(0).getName());
    Assert.assertEquals("Cookie value should be as defined",
            dummyCookieValue, result.get(0).getValue());

}
 
Example #9
Source File: HttpClient.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a Cookie by name and path
 *
 * @param name cookie name
 * @param path cookie path
 */
@PublicAtsApi
public void removeCookie( String name, String path ) {

    BasicCookieStore cookieStore = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
    if (cookieStore != null) {

        List<Cookie> cookies = cookieStore.getCookies();
        cookieStore.clear();
        for (Cookie cookie : cookies) {
            if (!cookie.getName().equals(name) || !cookie.getPath().equals(path)) {
                cookieStore.addCookie(cookie);
            }
        }
    }
}
 
Example #10
Source File: PreferencesCookieStore.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a persistent cookie store.
 */
public PreferencesCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
    cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
 
Example #11
Source File: HttpTest.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
public Cookie test01() throws IOException {
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8088/checkin");
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("username", "neiljianliu"));
    params.add(new BasicNameValuePair("userpwd", "*****"));
    params.add(new BasicNameValuePair("action", "login"));
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    CookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    HttpClientContext context = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        context = HttpClientContext.create();
        response = httpClient.execute(httpPost, context);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
    List<Cookie> cookies = context.getCookieStore().getCookies();
    return cookies.get(0);
}
 
Example #12
Source File: PersistentCookieStore.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie) {
    String name = cookie.getName();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store

    Set<String> keySet = cookies.keySet();
    userPreferences.setProperty(COOKIE_NAME_STORE,
            join(",", keySet));
    userPreferences.setProperty(COOKIE_NAME_PREFIX + name,
            encodeCookie(new SerializableCookie(cookie)));
    UserPreference.getInstance().saveUserPreferences();
}
 
Example #13
Source File: HttpRequestStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSetCookiesFromBrowserAndDelegateRequestToApiSteps()
{
    CookieStore cookieStore = mock(CookieStore.class);
    when(cookieManager.getCookiesAsHttpCookieStore()).thenReturn(cookieStore);
    BasicClientCookie cookie1 = new BasicClientCookie("key", "vale");
    BasicClientCookie cookie2 = new BasicClientCookie("key1", "vale1");
    when(cookieStore.getCookies()).thenReturn(List.of(cookie1, cookie2));
    httpRequestSteps.executeRequestUsingBrowserCookies();
    verify(httpTestContext).putCookieStore(cookieStore);
    verify(attachmentPublisher).publishAttachment(eq("org/vividus/bdd/steps/integration/browser-cookies.ftl"),
        argThat(arg ->
        {
            @SuppressWarnings("unchecked")
            List<Cookie> cookies = ((Map<String, List<Cookie>>) arg).get("cookies");
            return cookies.size() == 2
                    && cookies.get(0).toString().equals(
                            "[version: 0][name: key][value: vale][domain: null][path: null][expiry: null]")
                    && cookies.get(1).toString().equals(
                            "[version: 0][name: key1][value: vale1][domain: null][path: null][expiry: null]");
        }), eq("Browser cookies"));
}
 
Example #14
Source File: PersistentCookieStore.java    From Libraries-for-Android-Developers with MIT License 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie) {
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}
 
Example #15
Source File: HttpResult.java    From TvLauncher with Apache License 2.0 6 votes vote down vote up
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
    if (cookieStore != null) {
        this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
    }

    if (httpResponse != null) {
        this.headers = httpResponse.getAllHeaders();
        this.statuCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println(this.statuCode);
        try {
            this.response = EntityUtils.toByteArray(httpResponse.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 
Example #16
Source File: PersistentCookieStore.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public void reload() {
    //todo dir
    // Load any previously stored cookies into the store

    cookies = new ConcurrentHashMap<String, Cookie>();

    String storedCookieNames = userPreferences.getProperty(
            COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = userPreferences.getProperty(
                    COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
 
Example #17
Source File: PersistentCookieStore.java    From sealtalk-android with MIT License 6 votes vote down vote up
/**
 * Construct a persistent cookie store.
 *
 * @param context Context to attach cookie store to
 */
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
 
Example #18
Source File: PersistentCookieStore.java    From AndroidWear-OpenWear with MIT License 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie) {
    if (omitNonPersistentCookies && !cookie.isPersistent())
        return;
    String name = cookie.getName() + cookie.getDomain();

    // Save cookie into local store, or remove if expired
    if (!cookie.isExpired(new Date())) {
        cookies.put(name, cookie);
    } else {
        cookies.remove(name);
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
    prefsWriter.commit();
}
 
Example #19
Source File: PersistentCookieStore.java    From letv with Apache License 2.0 6 votes vote down vote up
public PersistentCookieStore(Context context) {
    int i = 0;
    this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        int length = cookieNames.length;
        while (i < length) {
            String name = cookieNames[i];
            String encodedCookie = this.cookiePrefs.getString(new StringBuilder(COOKIE_NAME_PREFIX).append(name).toString(), null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    this.cookies.put(name, decodedCookie);
                }
            }
            i++;
        }
        clearExpired(new Date());
    }
}
 
Example #20
Source File: CookieConverterTest.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidPath4() {
    String[] cookiesStrings = new String[1];
    String dummyCookieString = buildCookieString(dummyCookieHeader,
            dummyCookieValue, null, null, "/someFolder", null);
    cookiesStrings[0] = dummyCookieString;
    List<Cookie> result = CookieConverter.getCookies(cookiesStrings,
            getUrl(unsecuredUrl + "/someFolder/SomeOtherFolder"));
    Assert.assertEquals("Should have 1 cookie", 1, result.size());
    Assert.assertEquals("Cookie header should be as defined",
            dummyCookieHeader, result.get(0).getName());
    Assert.assertEquals("Cookie value should be as defined",
            dummyCookieValue, result.get(0).getValue());

}
 
Example #21
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
private String getCookieValue(CookieStore cookieStore, String cookieName) {
    String value = null;
    for (Cookie cookie : cookieStore.getCookies()) {

        if (cookie.getName().equals(cookieName)) {
            value = cookie.getValue();
        }
    }
    return value;
}
 
Example #22
Source File: SerializableCookie.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public Cookie getCookie() {
    Cookie bestCookie = cookie;
    if (clientCookie != null) {
        bestCookie = clientCookie;
    }
    return bestCookie;
}
 
Example #23
Source File: HttpKit.java    From tieba-api with MIT License 5 votes vote down vote up
/**
 * 获取cookies
 * @return Cookies
 */
public String getCookies() {
       StringBuilder sb = new StringBuilder();
       List<Cookie> list = this.getCookieStore().getCookies();
	for (Cookie cookie : list) {
		sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
	}
	return sb.toString();
   }
 
Example #24
Source File: PreferencesCookieStore.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
protected Cookie decodeCookie(String cookieStr) {
    byte[] bytes = hexStringToByteArray(cookieStr);
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    Cookie cookie = null;
    try {
       ObjectInputStream ois = new ObjectInputStream(is);
       cookie = ((SerializableCookie)ois.readObject()).getCookie();
    } catch (Exception e) {
       e.printStackTrace();
    }

    return cookie;
}
 
Example #25
Source File: PersistentCookieStore.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * Non-standard helper method, to delete cookie
 *
 * @param cookie cookie to be removed
 */
public void deleteCookie(Cookie cookie) {
    String name = cookie.getName() + cookie.getDomain();
    cookies.remove(name);
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.remove(COOKIE_NAME_PREFIX + name);
    prefsWriter.commit();
}
 
Example #26
Source File: AzkabanProjectService.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
private void uploadProject(String tmpSavePath, Project project, Cookie cookie) throws AppJointErrorException {
    String projectName = project.getName();
    HttpPost httpPost = new HttpPost(projectUrl + "?project=" + projectName);
    httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
    CloseableHttpResponse response = null;
    File file = new File(tmpSavePath);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    CloseableHttpClient httpClient = null;
    InputStream inputStream = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        MultipartEntityBuilder entityBuilder =  MultipartEntityBuilder.create();
        entityBuilder.addBinaryBody("file",file);
        entityBuilder.addTextBody("ajax", "upload");
        entityBuilder.addTextBody("project", projectName);
        httpPost.setEntity(entityBuilder.build());
        response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        inputStream = httpEntity.getContent();
        String entStr = null;
        entStr = IOUtils.toString(inputStream, "utf-8");
        if(response.getStatusLine().getStatusCode() != 200){
            logger.error("调用azkaban上传接口的返回不为200, status code 是 {}", response.getStatusLine().getStatusCode());
            throw new AppJointErrorException(90013, "release project failed, " + entStr);
        }
        logger.info("upload project:{} success!",projectName);
    }catch (Exception e){
        logger.error("upload failed,reason:",e);
        throw new AppJointErrorException(90014,e.getMessage(), e);
    }
    finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example #27
Source File: PersistentCookieStore.java    From Mobike with Apache License 2.0 5 votes vote down vote up
@Override
public boolean clearExpired(Date date) {
    boolean clearedAny = false;
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

    for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
        String name = entry.getKey();
        Cookie cookie = entry.getValue();
        if (cookie.isExpired(date)) {
            // Clear cookies from local store
            cookies.remove(name);

            // Clear cookies from persistent store
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);

            // We've cleared at least one
            clearedAny = true;
        }
    }

    // Update names in persistent store
    if (clearedAny) {
        prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    }
    prefsWriter.commit();

    return clearedAny;
}
 
Example #28
Source File: ResponseSender.java    From esigate with Apache License 2.0 5 votes vote down vote up
void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        response.addHeader(name, value);
    }

    // Copy new cookies
    Cookie[] newCookies = httpRequest.getNewCookies();

    for (Cookie newCooky : newCookies) {

        // newCooky may be null. In that case just ignore.
        // See https://github.com/esigate/esigate/issues/181
        if (newCooky != null) {
            response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCooky));
        }
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        long contentLength = httpEntity.getContentLength();
        if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }
        Header contentType = httpEntity.getContentType();
        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
        }
    }
}
 
Example #29
Source File: HttpProtocol.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
private void addCookiesToRequest(Builder rb, String url, Metadata md) {
    String[] cookieStrings = md.getValues(RESPONSE_COOKIES_HEADER, protocolMDprefix);
    if (cookieStrings == null || cookieStrings.length == 0) {
        return;
    }
    try {
        List<Cookie> cookies = CookieConverter.getCookies(cookieStrings,
                new URL(url));
        for (Cookie c : cookies) {
            rb.addHeader("Cookie", c.getName() + "=" + c.getValue());
        }
    } catch (MalformedURLException e) { // Bad url , nothing to do
    }
}
 
Example #30
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public List<Cookie> PostCookies(final String uri, final HttpEntity httpEntity) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpPost post = new HttpPost(uri);
    post.setEntity(httpEntity);
    client.execute(post);
    final List<Cookie> cookies = client.getCookieStore().getCookies();
    // client.getConnectionManager().shutdown();
    return cookies;
}