com.wizzardo.tools.http.HttpSession Maven / Gradle / Ivy
package com.wizzardo.tools.http;
import com.wizzardo.tools.misc.Unchecked;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author: wizzardo
* Date: 3/5/14
*/
public class HttpSession extends RequestArguments {
private Map> cookies = new ConcurrentHashMap>();
public HttpSession() {
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.187 Safari/535.1");
headers.put("Accept-Encoding", "gzip, deflate");
// headers.put("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.3");
}
public Request createRequest(String url) {
return super.createRequest(url)
.setSession(this)
.setCookies(getCookies(url));
}
@Override
protected HttpSession self() {
return this;
}
public List getCookies(String url) {
try {
return getCookies(new URL(url));
} catch (MalformedURLException e) {
throw Unchecked.rethrow(e);
}
}
public Map> getCookies() {
return cookies;
}
public List getCookies(URL url) {
List cookies = new ArrayList();
String domain = url.getHost();
while (domain.length() > 0) {
// System.out.println(domain);
List l = this.cookies.get(domain);
if (l != null) {
Iterator i = l.iterator();
while (i.hasNext()) {
Cookie cookie = i.next();
if (cookie.isExpired()) {
i.remove();
continue;
}
if ((url.getPath().isEmpty() ? "/" : url.getPath()).startsWith(cookie.path))
cookies.add(cookie);
}
}
int index = domain.indexOf('.');
if (index >= 0)
domain = domain.substring(index + 1);
else
break;
}
return cookies;
}
public void appendCookies(Map> cookies) {
this.cookies.putAll(cookies);
}
public synchronized void appendCookies(List cookies) {
outer:
for (Cookie cookie : cookies) {
String domain = cookie.domain.startsWith(".") ? cookie.domain.substring(1) : cookie.domain;
List l = this.cookies.get(domain);
if (cookie.value.equalsIgnoreCase("deleted") && l != null) {
Iterator i = l.iterator();
while (i.hasNext()) {
Cookie it = i.next();
if (it.key.equals(cookie.key) && it.domain.equals(cookie.domain))
i.remove();
}
} else {
if (l == null) {
l = new ArrayList();
this.cookies.put(domain, l);
}
for (Cookie it : l) {
if (it.key.equals(cookie.key) && it.domain.equals(cookie.domain)) {
it.expired = cookie.expired;
it.value = cookie.value;
continue outer;
}
}
l.add(cookie);
}
}
}
}