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

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

Introduction

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

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Get request/*  w ww .  j  a  v a  2s  .  co m*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        // Transfer bytes from in to out
        log.debug("HTTP GET: transferring...");

        //execute the GET
        String serverUrl = request.getParameter("url");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            log.info("GET param serverUrl:" + serverUrl);
            HttpClient client = new HttpClient();
            GetMethod httpget = new GetMethod(serverUrl);
            client.executeMethod(httpget);

            if (log.isDebugEnabled()) {
                Header[] respHeaders = httpget.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            //dump response to out
            if (httpget.getStatusCode() == HttpStatus.SC_OK) {
                //force the response to have XML content type (WMS servers generally don't)
                response.setContentType("text/xml");
                String responseBody = httpget.getResponseBodyAsString().trim();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
                response.flushBuffer();
            } else {
                log.error("Unexpected failure: " + httpget.getStatusLine().toString());
            }
            httpget.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:br.org.acessobrasil.silvinha.util.versoes.VerificadorDeVersoes.java

public boolean verificarVersao(Versao versaoCliente) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "check");
    method.setRequestBody(new NameValuePair[] { param });
    DefaultHttpMethodRetryHandler retryHandler = null;
    retryHandler = new DefaultHttpMethodRetryHandler(0, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    try {//from w  w  w  .  j  a  va2s.  co m
        //System.out.println(Silvinha.VERIFICADOR_VERSOES+client.getState().toString());
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String rb = new String(responseBody).trim();
        Versao versaoServidor = null;
        try {
            versaoServidor = new Versao(rb);
        } catch (NumberFormatException nfe) {
            return false;
        }
        if (versaoCliente.compareTo(versaoServidor) < 0) {
            AtualizadorDeVersoes av = new AtualizadorDeVersoes(url);
            return av.confirmarAtualizacao();
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }

}

From source file:fr.jayasoft.ivy.url.HttpClientHandler.java

public URLInfo getURLInfo(URL url, int timeout) {
    HeadMethod head = null;// w  w w . ja va  2s .c o m
    try {
        head = doHead(url, timeout);
        int status = head.getStatusCode();
        head.releaseConnection();
        if (status == HttpStatus.SC_OK) {
            return new URLInfo(true, getResponseContentLength(head), getLastModified(head));
        }
        if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            Message.error("Your proxy requires authentication.");
        } else if (String.valueOf(status).startsWith("4")) {
            Message.verbose("CLIENT ERROR: " + head.getStatusText() + " url=" + url);
        } else if (String.valueOf(status).startsWith("5")) {
            Message.warn("SERVER ERROR: " + head.getStatusText() + " url=" + url);
        }
        Message.debug("HTTP response status: " + status + "=" + head.getStatusText() + " url=" + url);
    } catch (HttpException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + ":" + e.getReasonCode() + "=" + e.getReason()
                + " url=" + url);
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info(
                "You probably access the destination server through a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + " url=" + url);
    } finally {
        if (head != null) {
            head.releaseConnection();
        }
    }
    return UNAVAILABLE;
}

From source file:com.agile_coder.poker.server.stories.steps.BaseSteps.java

protected String getStatus(int session) throws IOException {
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(BASE_URL + "/" + session + "/status");
    int result;// w  w w. j  ava  2 s.  co m
    String response;
    try {
        client.executeMethod(get);
        result = get.getStatusCode();
        response = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }
    assertEquals(HttpStatus.SC_OK, result);
    return response;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.util.RemoteIDPListEntry.java

/**
 * Retrieves the list.//w ww . j av a2 s  . c o m
 * 
 * @return The IDPList xml resource.
 * @throws ResourceException When list could not be fetched or is malformed.
 */
public IDPList getList() throws ResourceException {
    if (getLastModifiedTime().compareTo(new DateTime()) < 0 && _list != null) {
        //not modified lately
        _logger.debug("Resource not modified lately");
        return _list;
    }

    _logger.debug("Retrieving resource from URL " + getLocation());

    GetMethod m = super.getResource();

    try {
        _client.executeMethod(m);
        if (m.getStatusCode() == HttpStatus.SC_OK) {
            _list = unmarshall(m.getResponseBodyAsStream());
            _logger.debug("Resource successfully retrieved from URL " + getLocation());
            return _list;
        }

        StringBuffer buf = new StringBuffer("Retrieval of IDPList returned wrong HTTP status: ");
        buf.append(m.getStatusCode());
        throw new ResourceException(buf.toString());
    } catch (HttpException e) {
        throw new ResourceException("HTTP Error occurred", e);
    } catch (IOException e) {
        throw new ResourceException("I/O error occurred", e);
    }
}

From source file:com.tribune.uiautomation.testscripts.Photo.java

public static Photo find(String namespace, String slug) throws JSONException {
    if (namespace == null || slug == null) {
        return null;
    }//  w w w.j a v a 2 s .  com
    GetMethod get = new GetMethod(constructResourceUrl(namespace, slug));
    setRequestHeaders(get);
    Photo photo = null;

    try {
        HttpClient client = new HttpClient();
        int status = client.executeMethod(get);

        log.debug("Photo Service find return status: " + get.getStatusLine());

        if (status == HttpStatus.SC_OK) {
            photo = new Photo();
            processResponse(photo, get.getResponseBodyAsStream());
            photo.setPersisted(true);
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        get.releaseConnection();
    }

    return photo;
}

From source file:com.owncloud.android.lib.resources.files.SearchOperation.java

/** Check whether the request was successful */
private boolean checkSuccess(int status, GetMethod request) throws Exception {
    if (status != HttpStatus.SC_OK) {
        return false;
    }/*from   w w  w.j a  v a 2s  .com*/

    Header header = request.getResponseHeader("content-type");
    if (header == null) {
        throw new Exception("No content-type header");
    }

    //noinspection LoopStatementThatDoesntLoop
    do {
        HeaderElement[] elements = header.getElements();
        if (elements.length != 1) {
            break;
        }
        String type = elements[0].getName();
        if (!type.equalsIgnoreCase("application/json")) {
            break;
        }

        return true;
    } while (false);
    throw new Exception("Unsupported content type: " + header.getValue());
}

From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(TransportObject object) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;//from w  w w  . j  a va  2  s . c  o m
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        bOs = new ByteArrayOutputStream();
        dOs = new DataOutputStream(bOs);
        object.toStream(dOs);
        bOs.flush();
        rawData = bOs.toByteArray();

        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(object.getValue(SERVER_URL));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));

        // meth.setRequestBody(new String(rawData));
        // meth.setRequestBody(new String(rawData,"UTF-8"));

        byte[] base64Array = Base64.encode(rawData).getBytes();
        meth.setRequestBody(new String(base64Array));

        // System.out.println(new String(rawData));

        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

From source file:davmail.util.ClientCertificateTest.java

public void testConnect() throws IOException {
    GetMethod getMethod = new GetMethod("/testdir");
    httpClient.executeMethod(getMethod);
    assertEquals(HttpStatus.SC_OK, getMethod.getStatusCode());
    System.out.println(getMethod.getResponseBodyAsString());
}

From source file:com.sap.netweaver.porta.core.nw7.FileUploaderImpl.java

public String[] upload(File[] archives) throws CoreException {
    // check if there are any credentials already set
    if (client == null) {
        // trigger the mechanism for requesting user for credentials
        throw new NotAuthorizedException(FAULT_UNAUTHORIZED.getFaultReason());
    }/*from   w w w .j a  v  a2s.c o  m*/

    PostMethod method = null;
    try {
        Part[] parts = new Part[archives.length];
        for (int i = 0; i < archives.length; i++) {
            parts[i] = new FilePart(archives[i].getName(), archives[i]);
        }

        method = new PostMethod(url);
        method.setDoAuthentication(true);
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new NotAuthorizedException(FAULT_INVALID_CREDENTIALS.getFaultReason());
        } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NotAuthorizedException(FAULT_PERMISSION_DENIED.getFaultReason());
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            throw new NoWSGateException(null, url);
        } else if (statusCode != HttpStatus.SC_OK) {
            throw new CoreException(method.getStatusText());
        }

        InputStream responseStream = method.getResponseBodyAsStream();
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream));
        String line;
        List<String> paths = new ArrayList<String>();
        while ((line = responseReader.readLine()) != null) {
            paths.add(line);
        }
        responseReader.close();
        responseStream.close();

        return paths.toArray(new String[] {});
    } catch (HttpException e) {
        throw new CoreException(e);
    } catch (IOException e) {
        throw new CoreException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}