Я хочу сделать два запроса в одном сеансе.Как мне сделать это с помощью HttpContext? - PullRequest
0 голосов
/ 11 декабря 2018

У меня была та же проблема, тот же результат: «Не удалось проверить предоставленный токен CSRF, потому что ваш сеанс не был найден».

Но, в моем случае, я делаю два запроса и второйзапрос (POST) не работает.

Код здесь:

private List<Mandado> pesquisaExterna(Pessoa pessoa) throws UnsupportedEncodingException, IOException, URISyntaxException {
        this.httpClient = HttpClientBuilder.create().build();
        /* Estabelecendo a Sessão */
        Gson gson = new Gson();

    this.httpContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    this.httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);


    HttpPost post_auth = new HttpPost(this.URL_AUTENTICAR); // URL para request
    StringEntity postingString = new StringEntity(gson.toJson(this.authenticationRequestDTO)); // Objeto para POST
    post_auth.setEntity(postingString);

    post_auth.addHeader("content-type", MediaType.APPLICATION_JSON_VALUE); // definindo os headers
    post_auth.addHeader("cache-control", "no-cache");
    System.out.println("body: " + gson.toJson(this.authenticationRequestDTO));

    HttpResponse response;

    ObjectMapper mapper = new ObjectMapper();
    AuthenticationResponseDTO auth = new AuthenticationResponseDTO();

    String cookie = "";
    String result = "";

    try {
        response = this.httpClient.execute(post_auth, this.httpContext);
        String resp = MandadoBusiness.convertStreamToString(response.getEntity().getContent());
        System.out.println("resp1: " + resp);

        JsonNode authentication = mapper.readTree(resp);

        PessoaFilter filter = new PessoaFilter();

        if (pessoa.getNrCpf() != null && pessoa.getNrCpf().length() == 11) {
            DocumentoDTO doc = new DocumentoDTO();
            doc.setNumero(pessoa.getNrCpf());
            filter.setDocumento(doc);
        }


        List<NameValuePair> postParameters = new ArrayList<>(); //parâmetros do request
        postParameters.add(new BasicNameValuePair("page", "1"));
        postParameters.add(new BasicNameValuePair("size", "30"));

        URIBuilder uriBuilder = new URIBuilder(this.URL + "/api/pessoas/filter");
        uriBuilder.addParameters(postParameters);

        HttpPost post = new HttpPost(uriBuilder.build()); // URL para request

        postingString = new StringEntity(gson.toJson(filter)); // Objeto para POST
        post.setEntity(postingString);

        post.addHeader("content-type", MediaType.APPLICATION_JSON_VALUE); // definindo os headers
        post.addHeader("Cookie", authentication.get("token_csrf").asText());
        post.addHeader("X-XSRF-TOKEN", authentication.get("token_csrf").asText());
        post.addHeader("Authorization", "Bearer " + authentication.get("token_jwt").asText());

        // IMPRESSÃO DOS DETALHES DO REQUEST FEITO
        System.out.println("body: " + gson.toJson(filter));
        System.out.println("headers: " + Arrays.toString(post.getAllHeaders()));
        System.out.println("request_line: " + post.getRequestLine().toString());

        response = this.httpClient.execute(post,this.httpContext);

        if(response.getEntity() != null){
            result = MandadoBusiness.convertStreamToString(response.getEntity().getContent());
            System.out.println("Response: " + result);
        }else{
            System.out.println("Response with error!!");
        }

    } catch (IOException | UnsupportedOperationException e) {
        System.out.println("Msg: " + e.getMessage());
    }

    return gson.fromJson(result, ArrayList.class);
}

Кто-то может помочь мне разобраться в ошибке?

Пожалуйста, извините за мойужасный английский

...