HttpClient在发送发布数据时自动注销

时间:2013-11-02 11:59:19

标签: java apache httpclient

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

1 个答案:

答案 0 :(得分:0)

配方

您需要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);
// ...