0

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

1 回答 1

1

食谱

您需要 cookie 存储有一个地方来保存调用之间的会话 ID

代码

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);
// ...
于 2013-11-02T12:58:06.840 回答