0
我開始與編程Java和wan't創建一個簡單的「後端履帶」。爲此,我需要通過張貼登錄功能,那不是問題,但我可怎麼辦餅乾戰爭保存,並在下一次請求腳本並不需要再次登錄?Java的Apache的HTTP客戶端 - 保存的Cookie爲下一個請求
你能舉個例子嗎?我無法在互聯網上找到解決方案。
也許你可以解釋我怎麼可以用第一頁的Cookies做下一個請求? :)
希望你的答案。
對不起,我的英語不好。
這是我第一次Logintest:P
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Login {
public static String loginAndGetHTML() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
String html;
HttpPost HttpPost = new HttpPost("http://www.google.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "admin"));
nvps.add(new BasicNameValuePair("password", "1234"));
HttpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpPost.addHeader("Referer", "http://tutorials.amazingcode.de/login/index.php");
HttpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");
CloseableHttpResponse response = httpclient.execute(HttpPost);
try {
HttpEntity entity = response.getEntity();
html = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
if(html.contains("Falsche Nutzerdaten")) {
throw new Exception("Login fehlgeschlagen");
}
return html;
}
public static String parseHTML(String html) throws Exception {
Document doc = Jsoup.parse(html);
String zahl = doc.getElementById("zahl").text();
return zahl;
}
}
我嘗試讀取頭...但我找不到頭的cookie,所以我不能將它們保存 – Joni