Example usage for org.apache.commons.httpclient HttpStatus getStatusText

List of usage examples for org.apache.commons.httpclient HttpStatus getStatusText

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus getStatusText.

Prototype

public static String getStatusText(int statusCode) 

Source Link

Document

Get the reason phrase for a particular status code.

Usage

From source file:org.xmlblackbox.test.infrastructure.xml.HTTPUploader.java

public void uploadFile(MemoryData memory, HTTPUploader httpClient)
        throws TestException, HttpException, IOException {
    int ris;/*  w  ww . j av a 2 s  . c om*/
    HttpClient hClient = new HttpClient();

    Properties prop = memory.getOrCreateRepository(getRepositoryName());
    logger.info("prop " + prop);

    /**
     * Effettua la login
     */
    String usernameStr = (String) httpClient.getParameters().get("username");
    String passwordStr = (String) httpClient.getParameters().get("password");

    Properties fileProperties = memory.getOrCreateRepository(Repository.FILE_PROPERTIES);

    logger.info("Login al " + urlLogin);
    PostMethod postMethodLogin = new PostMethod(urlLogin);
    NameValuePair username = new NameValuePair();
    username.setName("userId");
    username.setValue(usernameStr);
    logger.info("username " + usernameStr);
    NameValuePair password = new NameValuePair();
    password.setName("password");
    password.setValue(passwordStr);
    logger.info("password " + passwordStr);

    if (usernameStr != null) {
        postMethodLogin.addParameter(username);
    }
    if (passwordStr != null) {
        postMethodLogin.addParameter(password);
    }
    ris = hClient.executeMethod(postMethodLogin);
    logger.debug("ris Login password " + passwordStr + " " + ris);

    if (ris != HttpStatus.SC_MOVED_TEMPORARILY) {
        throw new TestException("Error during login for uploading the file");
    }

    XmlObject[] domandeXml = null;

    File fileXML = new File(httpClient.getFileToUpload());
    PostMethod postm = new PostMethod(urlUpload);

    logger.debug("fileXML.getName() " + fileXML.getName());
    logger.debug("fileXML " + fileXML);
    logger.debug("postm.getParams()  " + postm.getParams());
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_NAME\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_NAME"));
    logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_VALUE\") "
            + httpClient.getParameters().get("OPERATION_UPLOAD_VALUE"));

    try {
        Part[] parts = {
                new StringPart(httpClient.getParameters().get("OPERATION_UPLOAD_NAME"),
                        httpClient.getParameters().get("OPERATION_UPLOAD_VALUE")),
                new FilePart("file", fileXML.getName(), fileXML) };

        postm.setRequestEntity(new MultipartRequestEntity(parts, postm.getParams()));
        logger.debug("parts " + parts);
    } catch (FileNotFoundException e2) {
        logger.error("FileNotFoundException ", e2);
        throw new TestException(e2, "FileNotFoundException ");
    }

    hClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);

    try {
        ris = hClient.executeMethod(postm);
        logger.info("ris Upload password " + passwordStr + " " + ris);
        logger.debug("ris Upload password " + passwordStr + " " + ris);
        if (ris == HttpStatus.SC_OK) {
            //logger.info("Upload completo, risposta=" + postm.getResponseBodyAsString());

            InputStream in = postm.getResponseBodyAsStream();
            //OutputStream out = new FileOutputStream(new File(prop.getProperty("FILE_RISPOSTA_SERVLET")));
            OutputStream out = new FileOutputStream(new File(httpClient.getFileOutput()));
            OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");

            BufferedReader bufferedReader = new BufferedReader(reader);

            // Transfer bytes from in to out
            //byte[] buf = new byte[1024];
            //int len;
            String linea = null;
            while ((linea = bufferedReader.readLine()) != null) {
                writer.write(linea);
            }
            writer.close();
            reader.close();
            in.close();
            out.close();

        } else {
            logger.error("Upload failed, response =" + HttpStatus.getStatusText(ris));
            logger.error("Exception : Server response not correct ");
            throw new TestException("Exception : Server response not correct ");
        }
    } catch (HttpException e) {
        logger.error("Exception : Server response not correct ", e);
        throw new TestException(e, "");
    } catch (IOException e) {
        logger.error("Exception : Server response not correct ", e);

        throw new TestException(e, "");
    } finally {
        postm.releaseConnection();
    }
}

From source file:pt.webdetails.browserid.BrowserIdVerifier.java

/**
 * Verify if the given assertion is valid
 * @param assertion The assertion as returned 
 * @param audience/* ww w.j  a v a2 s . c  o m*/
 * @return
 * @throws HttpException if an HTTP protocol exception occurs or the service returns a code not in the 200 range.
 * @throws IOException if a transport error occurs.
 * @throws JSONException if the result cannot be parsed as JSON markup
 */
public BrowserIdResponse verify(String assertion, String audience)
        throws HttpException, IOException, JSONException {

    if (StringUtils.isEmpty(assertion))
        throw new IllegalArgumentException("assertion is mandatory");
    if (StringUtils.isEmpty(audience))
        throw new IllegalArgumentException("audience is mandatory");

    HttpClient client = new HttpClient();

    //TODO: check certificate?

    PostMethod post = new PostMethod(url);

    post.addParameter("assertion", assertion);
    post.addParameter("audience", audience);

    try {

        int statusCode = client.executeMethod(post);

        if (isHttpResponseOK(statusCode)) {
            return new BrowserIdResponse(post.getResponseBodyAsString());
        } else
            throw new HttpException(HttpStatus.getStatusText(statusCode));

    } finally {
        post.releaseConnection();
    }

}

From source file:ru.paradoxs.bitcoin.http.HttpSession.java

public JSONObject sendAndReceive(JSONObject message) {
    PostMethod method = new PostMethod(uri.toString());

    try {//from w  ww  .java  2s .  c  om
        method.setRequestHeader("Content-Type", POST_CONTENT_TYPE);

        RequestEntity requestEntity = new StringRequestEntity(message.toString(), JSON_CONTENT_TYPE, null);
        method.setRequestEntity(requestEntity);

        getHttpClient().executeMethod(method);
        int statusCode = method.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpSessionException(
                    "HTTP Status - " + HttpStatus.getStatusText(statusCode) + " (" + statusCode + ")");
        }

        JSONTokener tokener = new JSONTokener(method.getResponseBodyAsString());
        Object rawResponseMessage = tokener.nextValue();
        JSONObject response = (JSONObject) rawResponseMessage;

        if (response == null) {
            throw new HttpSessionException("Invalid response type");
        }

        return response;
    } catch (HttpException e) {
        throw new HttpSessionException(e);
    } catch (IOException e) {
        throw new HttpSessionException(e);
    } catch (JSONException e) {
        throw new HttpSessionException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:st.happy_camper.flume.twitter.TwitterStreamingConnection.java

/**
 * @return/*from  w w w .j  a  v  a 2s. c  om*/
 */
private void doOpen() {
    int backoff = 10000;

    while (true) {
        PostMethod method = new PostMethod(URL);

        LOG.info("post: " + this.postContent);
        method.setParameter("track", this.postContent);
        try {
            int statusCode = httpClient.executeMethod(method);
            switch (statusCode) {
            case 200: {
                LOG.info("Connected.");
                this.method = method;
                this.reader = new BufferedReader(
                        new InputStreamReader(method.getResponseBodyAsStream(), "utf8"));
                return;
            }
            case 401:
            case 403:
            case 406:
            case 413:
            case 416: {
                String message = String.format("%d %s.", statusCode, HttpStatus.getStatusText(statusCode));
                LOG.warn(message);
                LOG.warn(method.getResponseBodyAsString());
                method.releaseConnection();

                throw new IllegalStateException(message);
            }
            case 420: {
                LOG.warn("420 Rate Limited.");
                method.releaseConnection();
                break;
            }
            case 500: {
                LOG.warn("500 Server Internal Error.");
                method.releaseConnection();
                break;
            }
            case 503: {
                LOG.warn("503 Service Overloaded.");
                method.releaseConnection();
                break;
            }
            default: {
                String message = "Unknown status code: " + statusCode;
                LOG.warn(message);
                method.releaseConnection();
            }
            }
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            method.releaseConnection();
        }

        int wait = rnd.nextInt(backoff) + 1;
        LOG.info(String.format("Retry after %d milliseconds.", wait));
        try {
            Thread.sleep(wait);
        } catch (InterruptedException e) {
            LOG.error(e.getMessage(), e);
        }
        if (backoff < 240000) {
            backoff *= 2;
            if (backoff >= 240000) {
                backoff = 240000;
            }
        }
    }
}