Java HttpURLConnection:重定向后已连接

Java HttpURLConnection:重定向后已连接,java,Java,我需要连接到一个web应用程序,如果请求的url未映射到应用程序中,该应用程序将执行HTTP重定向。(例如:/users->/users/)对于身份验证,我们使用基于令牌的方法,因此我必须在每个请求中发送令牌 当我在重定向后设置令牌时,我总是得到一个java.lang.IllegalStateException:ready connected。有人能帮我解决这个问题吗 以下是我所做的: try { // setup connection URL url = new URL

我需要连接到一个web应用程序,如果请求的url未映射到应用程序中,该应用程序将执行HTTP重定向。(例如:/users->/users/)对于身份验证,我们使用基于令牌的方法,因此我必须在每个请求中发送令牌

当我在重定向后设置令牌时,我总是得到一个
java.lang.IllegalStateException:ready connected
。有人能帮我解决这个问题吗

以下是我所做的:

try {
      // setup connection
      URL url = new URL(ENDPOINT + path);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod(method.toString().toUpperCase());
      connection.setInstanceFollowRedirects(false);

      // has the request been redirected?
      if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
        String newUrl = connection.getHeaderField("Location");
        connection = (HttpURLConnection) new URL(ENDPOINT + newUrl).openConnection();
      }

      if (useToken) {
        connection.addRequestProperty("Authorization", testToken);
      }

      // post data
      if (data != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", "application/json");
        String json = new Gson().toJson(data);
        try (OutputStream dataStream = connection.getOutputStream()) {
          dataStream.write(json.getBytes());
        }
      }


      // retrieve response
      String body = IOUtils.toString(connection.getInputStream());
      return new TestResponse(connection.getResponseCode(), body);
    } catch (IOException ex) {
      LOGGER.error(ex.getMessage());
      return null;
    }

我认为您应该设置
连接。setInstanceFlowRedirects(true)
这将使连接遵循HTTP重定向,然后删除

// has the request been redirected?
      if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
        String newUrl = connection.getHeaderField("Location");
        connection = (HttpURLConnection) new URL(ENDPOINT + newUrl).openConnection();

我无法从您的代码中看出为什么需要将
setInstanceFollowRedirects
设置为false

我尝试过,但没有设置带有令牌的授权标头。当我设置“Authorization”标头时,我尝试用
connection.disconnect()关闭现有连接,然后重新连接到重定向的端点,但这似乎没有帮助。