Example usage for org.apache.commons.httpclient HttpMethod getStatusCode

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusCode.

Prototype

public abstract int getStatusCode();

Source Link

Usage

From source file:com.kodokux.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*  w  ww  .  ja v  a 2s  . co m*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        String message = getErrorMessage(method);
        if (message.contains("API rate limit exceeded")) {
            throw new GithubRateLimitExceededException(message);
        }
        throw new GithubAuthenticationException("Request response: " + message);
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Build Http Exception from methode status
 *
 * @param method Http Method//w  w  w  .j  av  a 2  s . com
 * @return Http Exception
 */
public static HttpException buildHttpException(HttpMethod method) {
    int status = method.getStatusCode();
    StringBuilder message = new StringBuilder();
    message.append(status).append(' ').append(method.getStatusText());
    try {
        message.append(" at ").append(method.getURI().getURI());
        if (method instanceof CopyMethod || method instanceof MoveMethod) {
            message.append(" to ").append(method.getRequestHeader("Destination"));
        }
    } catch (URIException e) {
        message.append(method.getPath());
    }
    // 440 means forbidden on Exchange
    if (status == 440) {
        return new LoginTimeoutException(message.toString());
    } else if (status == HttpStatus.SC_FORBIDDEN) {
        return new HttpForbiddenException(message.toString());
    } else if (status == HttpStatus.SC_NOT_FOUND) {
        return new HttpNotFoundException(message.toString());
    } else if (status == HttpStatus.SC_PRECONDITION_FAILED) {
        return new HttpPreconditionFailedException(message.toString());
    } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        return new HttpServerErrorException(message.toString());
    } else {
        return new HttpException(message.toString());
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

private static int checkNTLM(HttpClient httpClient, HttpMethod currentMethod) throws IOException {
    int status = currentMethod.getStatusCode();
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(currentMethod) && !hasNTLM(httpClient)) {
        LOGGER.debug(//from   w  ww. jav a2  s . c  o  m
                "Received " + status + " unauthorized at " + currentMethod.getURI() + ", retrying with NTLM");
        resetMethod(currentMethod);
        addNTLM(httpClient);
        status = httpClient.executeMethod(currentMethod);
    }
    return status;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Test method header for supported authentication mode,
 * return true if Basic authentication is not available
 *
 * @param getMethod http method//  ww w . j  av a 2  s  .  c  om
 * @return true if only NTLM is enabled
 */
public static boolean acceptsNTLMOnly(HttpMethod getMethod) {
    Header authenticateHeader = null;
    if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        authenticateHeader = getMethod.getResponseHeader("WWW-Authenticate");
    } else if (getMethod.getStatusCode() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticateHeader = getMethod.getResponseHeader("Proxy-Authenticate");
    }
    if (authenticateHeader == null) {
        return false;
    } else {
        boolean acceptBasic = false;
        boolean acceptNTLM = false;
        HeaderElement[] headerElements = authenticateHeader.getElements();
        for (HeaderElement headerElement : headerElements) {
            if ("NTLM".equalsIgnoreCase(headerElement.getName())) {
                acceptNTLM = true;
            }
            if ("Basic realm".equalsIgnoreCase(headerElement.getName())) {
                acceptBasic = true;
            }
        }
        return acceptNTLM && !acceptBasic;

    }
}

From source file:com.zimbra.qa.unittest.TestZimbraHttpConnectionManager.java

public static void dumpResponse(int respCode, HttpMethod method, String prefix) throws IOException {

    prefix = prefix + " - ";

    // status//from  w  w w .  j av a2s .co  m
    int statusCode = method.getStatusCode();
    String statusLine = method.getStatusLine().toString();

    System.out.println(prefix + "respCode=" + respCode);
    System.out.println(prefix + "statusCode=" + statusCode);
    System.out.println(prefix + "statusLine=" + statusLine);

    // headers
    System.out.println(prefix + "Headers");
    Header[] respHeaders = method.getResponseHeaders();
    for (int i = 0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        // trim the CRLF at the end to save space
        System.out.println(prefix + header.trim());
    }

    // body
    byte[] bytes = ByteUtil.getContent(method.getResponseBodyAsStream(), 0);
    System.out.println(prefix + bytes.length + " bytes read");
    System.out.println(new String(bytes));
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

private static String getLocationValue(HttpMethod method) throws URIException {
    String locationValue = null;/*from  w  ww  .jav  a2  s.co m*/
    Header location = method.getResponseHeader("Location");
    if (location != null && isRedirect(method.getStatusCode())) {
        locationValue = location.getValue();
        // Novell iChain workaround
        if (locationValue.indexOf('"') >= 0) {
            locationValue = URIUtil.encodePath(locationValue);
        }
        // workaround for invalid relative location
        if (locationValue.startsWith("./")) {
            locationValue = locationValue.substring(1);
        }
    }
    return locationValue;
}

From source file:edu.du.penrose.systems.util.HttpClientUtils.java

/**
 * Get file from URL, directories are created and files overwritten.
 * /*w w w  . j a v  a  2 s  .co  m*/
 * 
 * @deprecated use  org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
 * @param requestUrl
 * @param outputPathAndFileName
 *
 * @return int request status code OR -1 if an exception occurred
 */
static public int getToFile(String requestUrl, String outputPathAndFileName) {
    int resultStatus = -1;

    File outputFile = new File(outputPathAndFileName);
    String outputPath = outputFile.getAbsolutePath().replace(outputFile.getName(), "");
    File outputDir = new File(outputPath);
    if (!outputDir.exists()) {
        outputDir.mkdir();
    }

    HttpClient client = new HttpClient();

    //   client.getState().setCredentials(
    //         new AuthScope("localhost", 7080, null ),
    //         new UsernamePasswordCredentials("nation", "nationPW") 
    //     );
    //   client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    //   method.setDoAuthentication( true );   
    //  client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {

        OutputStream os = new FileOutputStream(outputFile);

        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            os.write(bytes, 0, count);
            count = bis.read(bytes);
        }
        bis.close();
        os.close();
        resultStatus = method.getStatusCode();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return resultStatus;
}

From source file:com.discursive.jccook.httpclient.ConditionalGetExample.java

private void processResults(HttpMethod method) throws HttpException {
    if (method.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
        System.out.println("Content not modified since last request");
    } else {// w w  w. j  av  a 2 s  . com
        System.out.println("Get Method retrieved content.");
        entityTag = retrieveHeader(method, "ETag");
        lastModified = retrieveHeader(method, "Last-Modified");
        System.out.println("Entity Tag: " + entityTag);
        System.out.println("Last Modified: " + lastModified);
    }
}

From source file:edu.du.penrose.systems.util.HttpClientUtils.java

/**
 * Appends response form URL to a StringBuffer
 * /*ww  w .  j  ava2  s  . co  m*/
 * @param requestUrl
 * @param resultStringBuffer
 * @return int request status code OR -1 if an exception occurred
 */
static public int getAsString(String requestUrl, StringBuffer resultStringBuffer) {
    HttpClient client = new HttpClient();

    //   client.getState().setCredentials(
    //         new AuthScope("localhost", 7080, null ),
    //         new UsernamePasswordCredentials("nation", "nationPW") 
    //     );
    //   client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    // method.setDoAuthentication( true );   
    // client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {
        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        String datastr = null;
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            datastr = new String(bytes, 0, count);
            resultStringBuffer.append(datastr);
            count = bis.read(bytes);
        }
        bis.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return method.getStatusCode();
}

From source file:de.micromata.jira.rest.core.util.RestException.java

public RestException(HttpMethod method) {
    this.statusCode = method.getStatusCode();
    this.reasonPhrase = method.getStatusText();
    try {//  w  w  w  .j  a  va 2  s .c o m
        InputStream inputStream = method.getResponseBodyAsStream();
        if (inputStream != null) {
            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.setLenient(true);
            Gson gson = new Gson();
            restErrorMessage = gson.fromJson(jsonReader, ErrorBean.class);
        }
    } catch (IOException e) {
        // nothing to say
    } finally {
        method.releaseConnection();
    }

}