我有这个浏览器类:
public class browser{
private List<String> cookies;
private HttpURLConnection conn;
<....>
public String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language",
"en-GB,en;q=0.8,en-US;q=0.6,ro;q=0.4,fr;q=0.2");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
System.out.println(cookies);
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
&LT; ...&GT;
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
如果我的所有请求都来自MainApp,那么一切都很好:
public class main_program {
public static void main(String[] args) {
Browser br = new Browser();
Check_List users = new Check_List ();
br.GetPageContent(//some url) >> see the cookies and retrives the url fine
但是当我在我的主程序中做这样的事情时:
users.getList()
这是同一个包中从Browser类调用GetPageContent方法的另一个类,事情很奇怪:大部分请求都没有附加cookie。 该课程如下:
public class Check_List {
private HashMap<String, String> dictionar = new HashMap<String, String>();
public void getList(HashMap dictionar) {
http_handler webpage = new http_handler();
try {
Iterator it = dictionar.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
webpage.GetPageContent("http://example.com/profile.php?id="+pairs.getKey()+"&actionid=15");
System.out.println("I'am on user: " + pairs.getValue());