Java Code Examples for org.apache.http.HttpStatus#SC_MOVED_TEMPORARILY

The following examples show how to use org.apache.http.HttpStatus#SC_MOVED_TEMPORARILY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * 0000174: Redirect location with default port specified are incorrectly rewritten when preserveHost=true
 * <p>
 * http://www.esigate.org/mantisbt/view.php?id=174
 * 
 * <p>
 * Issue with default ports, which results in invalid url creation.
 * 
 * @throws Exception
 */
public void testRewriteRedirectResponseWithDefaultPortSpecifiedInLocation() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://www.foo.com:8080") //
            .set(Parameters.PRESERVE_HOST, true) //
            .build();

    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_MOVED_TEMPORARILY, "Found");
    // The backend server sets the port even if default (OK it should not
    // but some servers do it)
    response.addHeader("Location", "http://www.foo.com:80/foo/bar");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    request = TestUtils.createIncomingRequest("http://www.foo.com:80/foo");
    // HttpClientHelper will use the Host
    // header to rewrite the request sent to the backend
    // http://www.foo.com/foo
    CloseableHttpResponse driverResponse = driver.proxy("/foo", request.build());
    // The test initially failed with an invalid Location:
    // http://www.foo.com:80:80/foo/bar
    assertEquals("http://www.foo.com:80/foo/bar", driverResponse.getFirstHeader("Location").getValue());
}
 
Example 2
Source File: MyRedirectHandler.java    From Mobike with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 3
Source File: HttpUtils.java    From lorne_core with Apache License 2.0 6 votes vote down vote up
/**
 * 执行http请求方法
 *
 * @param httpClient
 * @param request
 * @return
 */
public static String execute(CloseableHttpClient httpClient, HttpRequestBase request) {
    String res = null;
    try {
        CloseableHttpResponse response = httpClient.execute(request, CookieContext.createHttpClientContext());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = response.getFirstHeader("Location").getValue();
            return get(location);
        }
        res = IOUtils.getStringFromInputStream(response);
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        try {
            httpClient.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return res;
}
 
Example 4
Source File: JCRSolutionDirectFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void throwExceptionOnBadResponse( Response response ) throws FileSystemException {
  final int status = response.getStatus();
  switch ( status ) {
    case HttpStatus.SC_OK:
      logger.debug( "OK" );
      // response OK => do not throw exception and continue execution
      break;

    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_MOVED_TEMPORARILY:
      logger.debug( "FORBIDDEN" );
      throw new FileSystemException( INVALID_USERNAME_OR_PASSWORD );

    default:
      logger.debug( "ERROR " + status );
      throw new FileSystemException( BAD_RESPONSE, status );
  }
}
 
Example 5
Source File: MyRedirectHandler.java    From AndroidWear-OpenWear with MIT License 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 6
Source File: MyRedirectHandler.java    From android-project-wo2b with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 7
Source File: MartiDiceRoller.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(
    final HttpRequest request, final HttpResponse response, final HttpContext context)
    throws ProtocolException {
  final URI uri = getLocationURI(request, response, context);
  final String method = request.getRequestLine().getMethod();
  if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
    return new HttpHead(uri);
  } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
    return new HttpGet(uri);
  } else {
    final int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT
        || status == HttpStatus.SC_MOVED_PERMANENTLY
        || status == HttpStatus.SC_MOVED_TEMPORARILY) {
      return RequestBuilder.copy(request).setUri(uri).build();
    }
    return new HttpGet(uri);
  }
}
 
Example 8
Source File: MyRedirectHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 9
Source File: MyRedirectHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 10
Source File: MyRedirectHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public boolean isRedirectRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (!enableRedirects) {
        return false;
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return true;
        default:
            return false;
    } //end of switch
}
 
Example 11
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if status is a redirect (various 30x values).
 *
 * @param status Http status
 * @return true if status is a redirect
 */
public static boolean isRedirect(int status) {
    return status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_SEE_OTHER
            || status == HttpStatus.SC_TEMPORARY_REDIRECT;
}
 
Example 12
Source File: DriverTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testRewriteRedirectResponse() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://www.foo.com:8080/");
    properties.put(Parameters.PRESERVE_HOST, "false");
    request = TestUtils.createIncomingRequest("http://www.bar.com/foo/");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_MOVED_TEMPORARILY, "Found");
    response.addHeader("Location", "http://www.foo.com:8080/somewhere/");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse = driver.proxy("/foo/", request.build());
    assertEquals("http://www.bar.com/somewhere/", driverResponse.getFirstHeader("Location").getValue());
}
 
Example 13
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void setData( final FileName file, final byte[] data ) throws FileSystemException {
  final String[] fileName = computeFileNames( file );
  final StringBuilder b = new StringBuilder();
  for ( int i = 0; i < fileName.length; i++ ) {
    if ( i != 0 ) {
      b.append( SLASH );
    }
    b.append( fileName[ i ] );
  }

  String service = MessageFormat.format( UPLOAD_SERVICE,
    URLEncoder.encodeUTF8( normalizePath( b.toString() ).replaceAll( "\\!", "%21" ).replaceAll( "\\+", "%2B" ) ) );
  final WebResource resource = client.resource( url + service );
  final ByteArrayInputStream stream = new ByteArrayInputStream( data );
  final ClientResponse response = resource.put( ClientResponse.class, stream );
  final int status = response.getStatus();

  if ( status != HttpStatus.SC_OK ) {
    if ( status == HttpStatus.SC_MOVED_TEMPORARILY
      || status == HttpStatus.SC_FORBIDDEN
      || status == HttpStatus.SC_UNAUTHORIZED ) {
      throw new FileSystemException( "ERROR_INVALID_USERNAME_OR_PASSWORD" );
    } else {
      throw new FileSystemException( "ERROR_FAILED", status );
    }
  }

  try {
    // Perhaps a New file was created. Refresh local tree model.
    this.refresh();
  } catch ( IOException e ) {
    // Ignore if unable to refresh
  }
}
 
Example 14
Source File: TwitterStatusListener.java    From spring4ws-demos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
private String unshorten(String url, int loop) {
	if (loop > 2) {
		return null;
	}
	try (CloseableHttpClient defaultHttpClient = HttpClientBuilder.create()
			.disableRedirectHandling().build()) {
		HttpHead head = new HttpHead(url);
		HttpResponse response = defaultHttpClient.execute(head);

		int status = response.getStatusLine().getStatusCode();
		if (status == HttpStatus.SC_MOVED_PERMANENTLY
				|| status == HttpStatus.SC_MOVED_TEMPORARILY) {
			Header locationHeader = response.getFirstHeader("location");
			if (locationHeader != null) {
				String value = locationHeader.getValue();
				if (!value.startsWith("http") && value.startsWith("/")) {
					value = "http:/" + value;
				}
				int nloop = loop + 1;
				return unshorten(value, nloop);
			}
		}
		else if (status >= 400 && status != HttpStatus.SC_METHOD_NOT_ALLOWED
				&& status != HttpStatus.SC_FORBIDDEN) {
			return null;
		}

	}
	catch (IllegalStateException | IOException e) {
		if (!(e instanceof SSLException || e instanceof ConnectException)) {
			// ignore this
		}
	}
	return url;
}
 
Example 15
Source File: HttpClientTools.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static boolean isRedirectStatus(int statusCode) {
  switch (statusCode) {
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
      return true;
    default:
      return false;
  }
}
 
Example 16
Source File: WebProxyCall.java    From aliyun-cupid-sdk with Apache License 2.0 5 votes vote down vote up
public void callWebProxy(String url) {
    String resultCode = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            resultCode = ResponseCode.CALLRESPONSEERROR;
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                if (responseString.contains("Spark Jobs") && responseString.contains("Stages")
                        && responseString.contains("Storage") && responseString.contains("Environment")
                        && responseString.contains("Executors")) {
                    resultCode = ResponseCode.CALLSUCCESS;
                }
            }
        } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            resultCode = ResponseCode.CALLFORBIDDEN;
        } else {
            resultCode = ResponseCode.OTHER_RESPONSE + String.valueOf(statusCode);
        }
    } catch (Exception e) {
        LOG.warn("WebProxyCall exception " + e.getMessage());
        resultCode = ResponseCode.CALLEXCEPTION;
    } finally {
        httpclient.close();
    }
    LOG.info("WebProxyCall result " + resultCode);
    if (!resultCode.equals(ResponseCode.CALLSUCCESS)) {
        System.exit(1);
    }
}
 
Example 17
Source File: HttpRequestHandler.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
private int computeStatus(int status) {
    switch (status) { 
        case HttpStatus.SC_FORBIDDEN:
        case HttpStatus.SC_METHOD_NOT_ALLOWED:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_PAYMENT_REQUIRED:
        case HttpStatus.SC_NOT_FOUND:
        case HttpStatus.SC_NOT_ACCEPTABLE:
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        case HttpStatus.SC_REQUEST_TIMEOUT:
        case HttpStatus.SC_CONFLICT:
        case HttpStatus.SC_GONE:
        case HttpStatus.SC_LENGTH_REQUIRED:
        case HttpStatus.SC_PRECONDITION_FAILED:
        case HttpStatus.SC_REQUEST_TOO_LONG:
        case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
        case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
        case HttpStatus.SC_EXPECTATION_FAILED:
        case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
        case HttpStatus.SC_METHOD_FAILURE:
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
        case HttpStatus.SC_LOCKED:
        case HttpStatus.SC_FAILED_DEPENDENCY:
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        case HttpStatus.SC_NOT_IMPLEMENTED:
        case HttpStatus.SC_BAD_GATEWAY:
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
        case HttpStatus.SC_GATEWAY_TIMEOUT:
        case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
        case HttpStatus.SC_INSUFFICIENT_STORAGE:
            return 0;
        case HttpStatus.SC_CONTINUE:
        case HttpStatus.SC_SWITCHING_PROTOCOLS:
        case HttpStatus.SC_PROCESSING:
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
        case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
        case HttpStatus.SC_NO_CONTENT:
        case HttpStatus.SC_RESET_CONTENT:
        case HttpStatus.SC_PARTIAL_CONTENT:
        case HttpStatus.SC_MULTI_STATUS:
        case HttpStatus.SC_MULTIPLE_CHOICES:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_NOT_MODIFIED:
        case HttpStatus.SC_USE_PROXY:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return 1;
        default : 
            return 1;
    }
}
 
Example 18
Source File: PentahoParameterRefreshHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread
 * causes the object's <code>run</code> method to be called in that separately executing thread.
 * <p/>
 * The general contract of the method <code>run</code> is that it may take any action whatsoever.
 *
 * @see Thread#run()
 */
public void run() {
  pathModel.setLoginData( loginData );

  final String paramServiceText = getParameterServicePath( loginData, pathModel );
  if ( paramServiceText == null ) {
    return;
  }

  try {
    final HttpClient httpClient = createHttpClient( loginData );

    final HttpGet method = new HttpGet( paramServiceText );

    /*
     * With the work done for BISERVER-13648, the server no longer return an auth challenge to the issued request;
     * ( when this used to be the case, the HttpClient lib would handle such a 401 response OOTB by issuing the credentials
     * should any have been set in the HTTPContext ).
     *
     * Now ( i.e. post BISERVER-13648 ), the server returns a 302 REDIRECT to the server's /Login page.
     * We can circumvent by defining an  HttpClientContext with preemptive authentication set.
     */
    HttpClientContext httpCtx = buildPreemptiveAuthRequestContext( new URI( paramServiceText ), loginData );
    HttpResponse httpResponse = httpCtx != null ? httpClient.execute( method, httpCtx ) : httpClient.execute( method );
    final int result = httpResponse.getStatusLine().getStatusCode();
    if ( result != HttpStatus.SC_OK ) {
      if ( result == HttpStatus.SC_MOVED_TEMPORARILY || result == HttpStatus.SC_FORBIDDEN
        || result == HttpStatus.SC_UNAUTHORIZED ) {
        // notify the world that the login data is no longer valid
        throw new PublishException( PublishException.ERROR_INVALID_USERNAME_OR_PASSWORD );
      } else {
        throw new PublishException( PublishException.ERROR_FAILED, result );
      }
    }
    final byte[] responseBody = HttpClientUtil.responseToByteArray( httpResponse );
    final ResourceManager manager = new ResourceManager();
    final Resource resource = manager.createDirectly( responseBody, ParameterDocument.class );
    final ParameterDocument o = (ParameterDocument) resource.getResource();
    parameters = o.getParameter();
  } catch ( Exception e ) {
    error = e;
  }
}
 
Example 19
Source File: ExceptionUtils.java    From flink-crawler with Apache License 2.0 4 votes vote down vote up
public static FetchStatus mapHttpStatusToFetchStatus(int httpStatus) {
    switch (httpStatus) {
        case HttpStatus.SC_OK:
            return FetchStatus.FETCHED;

        case HttpStatus.SC_FORBIDDEN:
            return FetchStatus.HTTP_FORBIDDEN;

        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            return FetchStatus.HTTP_UNAUTHORIZED;

        case HttpStatus.SC_NOT_FOUND:
            return FetchStatus.HTTP_NOT_FOUND;

        case HttpStatus.SC_GONE:
            return FetchStatus.HTTP_GONE;

        case HttpStatus.SC_TEMPORARY_REDIRECT:
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_SEE_OTHER:
            return FetchStatus.HTTP_TOO_MANY_REDIRECTS;

        case HttpStatus.SC_MOVED_PERMANENTLY:
            return FetchStatus.HTTP_MOVED_PERMANENTLY;

        default:
            if (httpStatus < 300) {
                LOGGER.warn("Invalid HTTP status for exception: " + httpStatus);
                return FetchStatus.HTTP_SERVER_ERROR;
            } else if (httpStatus < 400) {
                return FetchStatus.HTTP_REDIRECTION_ERROR;
            } else if (httpStatus < 500) {
                return FetchStatus.HTTP_CLIENT_ERROR;
            } else if (httpStatus < 600) {
                return FetchStatus.HTTP_SERVER_ERROR;
            } else {
                LOGGER.warn("Unknown status: " + httpStatus);
                return FetchStatus.HTTP_SERVER_ERROR;
            }
    }
}
 
Example 20
Source File: O365Authenticator.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
private String authenticateADFS(HttpClientAdapter httpClientAdapter, String responseBodyAsString, String authorizeUrl) throws IOException {
    URI location;

    if (responseBodyAsString.contains("login.microsoftonline.com")) {
        LOGGER.info("Already authenticated through Basic or NTLM");
    } else {
        // parse form to get target url, authenticate as userid
        PostRequest logonMethod = new PostRequest(extract("method=\"post\" action=\"([^\"]+)\"", responseBodyAsString));
        logonMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        logonMethod.setParameter("UserName", userid);
        logonMethod.setParameter("Password", password);
        logonMethod.setParameter("AuthMethod", "FormsAuthentication");

        httpClientAdapter.executePostRequest(logonMethod);
        location = logonMethod.getRedirectLocation();
        if (location == null) {
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        }

        GetRequest redirectMethod = new GetRequest(location);
        responseBodyAsString = httpClientAdapter.executeGetRequest(redirectMethod);
    }

    if (!responseBodyAsString.contains("login.microsoftonline.com")) {
        throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
    }
    String targetUrl = extract("action=\"([^\"]+)\"", responseBodyAsString);
    String wa = extract("name=\"wa\" value=\"([^\"]+)\"", responseBodyAsString);
    String wresult = extract("name=\"wresult\" value=\"([^\"]+)\"", responseBodyAsString);
    // decode wresult
    wresult = wresult.replaceAll("&quot;", "\"");
    wresult = wresult.replaceAll("&lt;", "<");
    wresult = wresult.replaceAll("&gt;", ">");
    String wctx = extract("name=\"wctx\" value=\"([^\"]+)\"", responseBodyAsString);
    wctx = wctx.replaceAll("&amp;", "&");

    PostRequest targetMethod = new PostRequest(targetUrl);
    targetMethod.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    targetMethod.setParameter("wa", wa);
    targetMethod.setParameter("wresult", wresult);
    targetMethod.setParameter("wctx", wctx);

    responseBodyAsString = httpClientAdapter.executePostRequest(targetMethod);
    location = targetMethod.getRedirectLocation();

    LOGGER.debug(targetMethod.getURI().toString());
    LOGGER.debug(targetMethod.getReasonPhrase());
    LOGGER.debug(responseBodyAsString);

    if (targetMethod.getStatusCode() == HttpStatus.SC_OK) {
        JSONObject config = extractConfig(responseBodyAsString);
        if (config.optJSONArray("arrScopes") != null || config.optJSONArray("urlPostRedirect") != null) {
            LOGGER.debug("Authentication successful but user consent or validation needed, please open the following url in a browser");
            LOGGER.debug(authorizeUrl);
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        }
    } else if (targetMethod.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY || location == null) {
        throw new IOException("Unknown ADFS authentication failure");
    }

    if ("device.login.microsoftonline.com".equals(location.getHost())) {
        location = processDeviceLogin(httpClientAdapter, location);
    }
    String query = location.getQuery();
    if (query == null) {
        // failover for null query with non https URI like urn:ietf:wg:oauth:2.0:oob?code=...
        query = location.getSchemeSpecificPart();
    }

    if (query.contains("code=") && query.contains("&session_state=")) {
        String code = query.substring(query.indexOf("code=") + 5, query.indexOf("&session_state="));
        LOGGER.debug("Authentication Code: " + code);
        return code;
    }
    throw new IOException("Unknown ADFS authentication failure");
}