我有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());

最佳答案

食谱


准备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);
// ...

09-12 00:19