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:br.org.acessobrasil.silvinha.autenticador.AutenticadorConector.java

public boolean autenticarLogin(Login login) {
    boolean autenticado = false;
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair x1 = new NameValuePair("x1", login.getUser());
    NameValuePair x2 = new NameValuePair("x2", login.getPass());
    method.setRequestBody(new NameValuePair[] { x1, x2 });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {//from  w ww .java  2s.  com
        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();
        // Deal with the response.
        if (rb.startsWith("OK")) {
            autenticado = true;
            String[] rbLines = rb.split("\n");
            Token.setUrl(rbLines[1]);
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
    } finally {
        /*
         *  Release the connection.
        */
        method.releaseConnection();
    }

    return autenticado;
}

From source file:com.gargoylesoftware.htmlunit.html.XHtmlPageTest.java

/**
 * Tests a simplified real-life response from Ajax4jsf. Originally located in
 * {@link com.gargoylesoftware.htmlunit.xml.XmlPageTest}.
 * @throws Exception if an error occurs//  w w  w.j  av  a 2s.  com
 */
@Test
public void a4jResponse() throws Exception {
    final String content = "<html xmlns='http://www.w3.org/1999/xhtml'><head>" + "<script src='//:'></script>"
            + "</head><body><span id='j_id216:outtext'>Echo Hello World</span></body></html>";
    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(content, 200, "OK", "text/xml");
    client.setWebConnection(webConnection);
    final Page page = client.getPage(URL_FIRST);
    assertEquals(URL_FIRST, page.getWebResponse().getRequestSettings().getUrl());
    assertEquals("OK", page.getWebResponse().getStatusMessage());
    assertEquals(HttpStatus.SC_OK, page.getWebResponse().getStatusCode());
    assertEquals("text/xml", page.getWebResponse().getContentType());
    assertTrue(XHtmlPage.class.isInstance(page));
}

From source file:com.epam.wilma.service.http.WilmaHttpClient.java

private boolean executeCall(final HttpMethodBase methodBase, final String url) {
    boolean requestSuccessful = false;
    try {/*from  w w  w  .  j a v a  2  s  .  c  o m*/
        int statusCode = httpclient.executeMethod(methodBase);
        if (HttpStatus.SC_OK == statusCode) {
            requestSuccessful = true;
        }
    } catch (HttpException e) {
        LOG.error("Protocol exception occurred when called: " + url, e);
    } catch (IOException e) {
        LOG.error("I/O (transport) error occurred when called: " + url, e);
    }

    return requestSuccessful;
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

protected static boolean executeMethod(HttpClient client, HttpMethod method, StringBuffer response) {
    boolean success = true;
    try {/*w ww  . j  a  v a  2s .  co m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        if (response != null)
            response.append(new String(responseBody));
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        //  System.err.println("Fatal protocol violation: " + e.getMessage());
        // e.printStackTrace();
        success = false;
    } catch (IOException e) {
        //  System.err.println("Fatal transport error: " + e.getMessage());
        //  e.printStackTrace();
        success = false;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return success;
}

From source file:com.interaction.example.odata.multicompany.ODataMulticompanyITCase.java

@Test
public void testGetServiceDocumentBaseUri() throws Exception {
    org.apache.abdera.model.Service service = null;
    GetMethod method = new GetMethod(baseUri);
    try {/*  w  w  w  .  j a va  2s .c  o m*/
        client.executeMethod(method);
        assertEquals(200, method.getStatusCode());

        if (method.getStatusCode() == HttpStatus.SC_OK) {
            // read as string for debugging
            String response = method.getResponseBodyAsString();
            System.out.println("Response = " + response);

            Abdera abdera = new Abdera();
            Parser parser = abdera.getParser();
            Document<org.apache.abdera.model.Service> doc = parser.parse(new StringReader(response));
            service = doc.getRoot();
        }
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        method.releaseConnection();
    }

    assertNotNull(service);
    assertEquals("http://localhost:8080/example/interaction-odata-multicompany.svc/MockCompany001/",
            service.getBaseUri().toString());
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

public void testRallyRestServiceBuildSuccess() throws Exception {
    String xml = readFile(BUILD_SUCCESS_FILE);
    httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock), HttpStatus.SC_OK);
    postMethodMockControl.expectAndReturn(postMethodMock.getResponseBodyAsStream(),
            readFileAsStream(BUILD_SUCCESS_RESPONSE_FILE));
    postMethodMock.releaseConnection();//from   w w  w.  ja  v a  2s  .  c  o  m
    httpClientMockControl.replay();
    postMethodMockControl.replay();

    String response = rallyRestService.doCreate(xml, httpClientMock, postMethodMock);
    assertEquals(readFile(BUILD_SUCCESS_RESPONSE_FILE), response);
    verify();
}

From source file:de.bermuda.arquillian.example.ContentTypeProxyTest.java

private PostMethod postRequest(String body, String localPath) {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(BASE_URL + "/proxy" + localPath);
    try {/*from   w  ww.  ja  va  2  s  . co m*/
        StringRequestEntity entity = new StringRequestEntity(body, "application/soap+xml", "UTF-8");
        postMethod.setRequestEntity(entity);
    } catch (IOException e) {
        Assert.assertTrue("Catched IOException", false);
    }
    try {
        int status = client.executeMethod(postMethod);
        Assert.assertEquals("Expected OK", status, HttpStatus.SC_OK);
    } catch (HttpException e) {
        Assert.assertFalse("HttpException", true);
    } catch (IOException e) {
        Assert.assertFalse("IOException", true);
    }
    return postMethod;
}

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

public void testWsdlServletZimbraAdminServicesWsdl() throws Exception {
    String body = doWsdlServletRequest(wsdlUrlBase + "ZimbraAdminService.wsdl", true, HttpStatus.SC_OK);
    assertTrue("Body contains expected string", body.contains("wsdl:service name="));
}

From source file:at.ait.dme.yuma.server.image.ImageTilesetGenerator.java

private String storeImage(String dir, String url) throws TilesetGenerationException {
    InputStream is = null;//w w w .  j  a va  2s .  co m
    OutputStream os = null;
    try {
        GetMethod getImageMethod = new GetMethod(url);
        int statusCode = new HttpClient().executeMethod(getImageMethod);
        if (statusCode != HttpStatus.SC_OK)
            throw new TilesetGenerationException("GET " + url + " returned status code:" + statusCode);

        is = getImageMethod.getResponseBodyAsStream();
        File imageFile = new File(dir + "/" + url.substring(url.lastIndexOf("/")));
        os = new FileOutputStream(imageFile);

        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0)
            os.write(buf, 0, len);

        return imageFile.getAbsolutePath();
    } catch (Throwable t) {
        logger.error("failed to store image from url:" + url, t);
        throw new TilesetGenerationException(t);
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        } catch (IOException e) {
            logger.error("failed to close streams");
        }

    }
}

From source file:ch.ksfx.web.services.spidering.http.WebEngine.java

public void loadResource(Resource resource) {
    HttpMethod httpMethod;// w  w w. java2 s.c  om

    try {
        if (/*resource.getHttpMethod().equals(GET)*/true) {
            String url = resource.getUrl();

            if (url != null) {
                url = url.replaceAll("&amp;", "&");
                url = url.replaceAll("&quot;", "\"");
            }

            httpMethod = this.httpClientHelper.executeGetMethod(url);
        } else {
            //TODO implement POST functionality
            /*
            NameValuePair[] nameValuePairs = new NameValuePair[resource.getPostData().size()];
            for(int i = 0; i < resource.getPostData().size(); i++) {
            nameValuePairs[i] = new NameValuePair(resource.getPostData().get(i).getName(),
                                                  resource.getPostData().get(i).getValue());
            }
                    
            String url = resource.getURL().toString();
                    
            if (url != null) {
               url = url.replaceAll("&amp;","&");
               url = url.replaceAll("&quot;","\"");
            }
                    
            httpMethod = this.httpClientHelper.executePostMethod(url,
                                                             nameValuePairs);
             */
        }

    } catch (Exception e) {
        resource.setLoadSucceed(false);
        resource.setHttpStatusCode(222);

        logger.log(Level.SEVERE, "Unable to load resource", e);
        return;
    }

    if (httpMethod == null) {
        resource.setLoadSucceed(false);
        return;
    }

    if (httpMethod.getStatusCode() != HttpStatus.SC_OK) {
        try {
            resource.setUrl(httpMethod.getURI().toString());

            for (Header header : httpMethod.getResponseHeaders()) {
                resource.addResponseHeader(new ResponseHeader(header.getName(), header.getValue()));
            }
            resource.setHttpStatusCode(httpMethod.getStatusCode());
        } catch (Exception e) {
            logger.warning(e.getMessage());
            e.printStackTrace();
        }

        return;
    }

    try {
        if (httpMethod.getResponseHeader("Content-Encoding") != null
                && httpMethod.getResponseHeader("Content-Encoding").getValue().contains("gzip")) {
            BufferedInputStream in = new BufferedInputStream(
                    new GZIPInputStream(httpMethod.getResponseBodyAsStream()));
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) >= 0) {
                out.write(buffer, 0, length);
            }

            resource.setRawContent(out.toByteArray());
            resource.setSize(new Long(out.toByteArray().length));
        } else {
            BufferedInputStream in = new BufferedInputStream(httpMethod.getResponseBodyAsStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) >= 0) {
                out.write(buffer, 0, length);
            }

            resource.setRawContent(out.toByteArray());
            resource.setSize(new Long(out.toByteArray().length));
        }

        resource.setHttpStatusCode(httpMethod.getStatusCode());
        resource.setLoadSucceed(true);

        resource.setMimeType(recognizeMimeType(resource, httpMethod));
        if (resource.getMimeType().startsWith("text") || resource.getMimeType().equals("application/json")) {

            resource.setContent(EncodingHelper.encode(resource.getRawContent(), resource.getEncoding(),
                    ((HttpMethodBase) httpMethod).getResponseCharSet()));
        } else {
            resource.setIsBinary(true);
        }

    } catch (IOException e) {
        e.printStackTrace();
        logger.log(Level.SEVERE, "Unable to load resource", e);
    } finally {
        httpMethod.releaseConnection();
    }
}