我有方法sendPost(),它发送一个帖子数据登录到某个站点。我能够得到302的响应代码。执行此方法后,我有一个sendPost2()方法,如果我成功登录将会有效。但是,我在sendPost2()中得到响应代码200,它也告诉我我没有登录。似乎在执行sendPost()之后,httpclient将我退出。你如何防止它退出?
这是我的sendPost(),但我不能给你一个有效的用户名和密码:
private void sendPost() throws Exception {
String url = "http://sblive.auf.edu.ph/schoolbliz/commfile/login.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user_id", "testusername"));
urlParameters.add(new BasicNameValuePair("password", "testpassword"));
urlParameters.add(new BasicNameValuePair("x", "47"));
urlParameters.add(new BasicNameValuePair("y", "1"));
urlParameters.add(new BasicNameValuePair("body_color", "#9FBFD0"));
urlParameters.add(new BasicNameValuePair("welcome_url", "../PARENTS_STUDENTS/main_files/login_success.htm"));
urlParameters.add(new BasicNameValuePair("login_type", "parent_student"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
答案 0 :(得分:0)
CookieStore
HttpContext
HttpClient#execute()
调用您需要Cookie商店才能有keep the session ID between calls的位置。
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// ...
HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...
HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...