如何在一个会话中发送GET和POST请求?

时间:2016-03-10 10:15:42

标签: java apache-httpclient-4.x

我发送GET请求并解析对VIEWSTATEEVENTVALIDATION的响应。 然后我发送带有参数的POST请求,但变量无效! 那么,如何在一个会话中发送GETPOST个请求?页面在这里http://www.aogc2.state.ar.us:8080/DWClient/Login.aspx

这是我的代码

HttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
                .build();
private String sendGet() throws IOException {
        HttpGet httpget = new HttpGet(url+"Login.aspx");
        httpget.addHeader("User-Agent",USER_AGENT);
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            HttpEntity entity = response.getEntity();
            BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuilder result=new StringBuilder();
            String line;
            while ((line=br.readLine())!=null){
                result.append(line);
            }
            EntityUtils.consume(entity);
            updateViewState(result.toString());
            return result.toString();
        }
    }

    private String sendPost() throws IOException, URISyntaxException {
        HttpRequest login = RequestBuilder.post()
                .setUri(new URI(url+"Login.aspx"))
                .addParameter("DWC$DWMessages", "")
                .addParameter("__VIEWSTATE", viewState)
                .addParameter("__EVENTVALIDATION", eventValidation)
                .addParameter("DWC_NotificationToolTip_ClientState", "")
                .addParameter("LoginWebPart$LoginTypes", "Guest")
                .addParameter("LoginWebPart$TextBoxUserName", "")
                .addParameter("LoginWebPart$TextBoxPassword", "")
                .addParameter("LoginWebPart$ButtonLogin", "Login")
                .addParameter("LoginWebPart_LanguageContextMenu_ClientState", "")
                .addHeader("User-Agent",USER_AGENT)
                .build();
        try (CloseableHttpResponse response2 = httpclient.execute((HttpUriRequest)login)) {
            HttpEntity entity = response2.getEntity();
            BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuilder result=new StringBuilder();
            String line;
            while ((line=br.readLine())!=null){
                result.append(line);
            }
            EntityUtils.consume(entity);
            return result.toString();
        }
    }

0 个答案:

没有答案