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

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

Introduction

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

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:ensen.controler.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;/*from w  w w .ja v a2s  .  c o m*/

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        InputStream responseBodyStream = method.getResponseBodyAsStream(); //Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        int b = responseBodyStream.read();
        ArrayList<Integer> bytes = new ArrayList<Integer>();
        while (b != -1) {
            bytes.add(b);
            b = responseBodyStream.read();
        }
        byte[] responseBody = new byte[bytes.size()];

        for (int i = 0; i < bytes.size(); i++) {
            responseBody[i] = bytes.get(i).byteValue();
        }
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        System.out.println("Fatal protocol violation: " + e.getMessage());
        try {
            System.err.println(method.getURI());
        } catch (URIException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        System.out.println("Fatal transport error: " + e.getMessage());
        System.out.println(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message.//from w ww  .  ja va2s.  c om
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
protected String get(HttpMethod authgets, ContentProcessable cp)
        throws IOException, CookieException, ProcessException {
    showCookies(client);
    String out = "";
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    cp.validateReturningCookies(client.getState().getCookies(), authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBodyAsString();

    out = cp.processReturningText(out, authgets);
    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}

From source file:autohit.call.modules.SimpleHttpModule.java

/**
 * Start method. It will set the target address for the client, as well as
 * clearing any state.//from ww  w  . j av a 2 s.c o  m
 * 
 * @param url
 *            the Url path, not to include protocol, address, and port (ie.
 *            "/goats/index.html").
 * @return the data from the page as a String
 * @throws CallException
 */
private String get(String url) throws CallException {

    if (started == false) {
        throw buildException("module:SimpleHttp:Tried to get when a session wasn't started.",
                CallException.CODE_MODULE_FAULT);
    }

    String result = null;

    // Construct our method.
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);

    //execute the method
    try {
        // Do it
        debug("(get)get=" + url);
        httpClient.executeMethod(method);

        // Process result
        result = method.getResponseBodyAsString();
        log("(get)" + method.getStatusLine().toString() + " size=" + result.length());

    } catch (HttpException he) {
        // Bad but not fatal
        error("(get)Error on connect to url " + url + ".  Error=" + he.getMessage());
    } catch (IOException ioe) {
        // Fatal
        throw buildException("(get)Unable to connect.  Session is invalid.  message=" + ioe.getMessage(),
                CallException.CODE_MODULE_FAULT, ioe);
    } finally {
        try {
            method.releaseConnection();
            method.recycle();
        } catch (Exception e) {
            // Already FUBAR
        }
    }
    return result;
}

From source file:application.draw.SaveButtonDebuggFrame.java

private void connectButtonActionPerformed(ActionEvent evt) {
    System.out.println("connectButton.actionPerformed, event=" + evt);
    //TODO add your code for connectButton.actionPerformed

    client = new HttpClient();
    String url = this.urlField.getText();
    this.messageTextArea.append(url + "\n");
    try {// ww w. j av a 2  s .c  om
        HttpMethod method = new GetMethod(url);
        //          method.getParams().setContentCharset("UTF-8");
        int status = client.executeMethod(method);
        if (status != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        } else {
            //          String txt=method.getResponseBodyAsString();
            InputStream is = method.getResponseBodyAsStream();
            InputStreamReader isr = new InputStreamReader(is, this.charset);
            //               InputStreamReader isr=new InputStreamReader(is,"UTF-8");
            //               InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while (true) {
                line = br.readLine();
                if (line == null)
                    break;
                this.messageTextArea.append(line + "\n");
                //                 System.out.println(line);
            }
        }
    } catch (Exception e) {
        this.messageTextArea.append(e.toString() + "\n");
        e.printStackTrace();
    }

}

From source file:com.zimbra.qa.unittest.prov.soap.TestAutoProvision.java

@Test
public void preauthServlet() throws Exception {
    String testName = getTestName();

    String externalPassword = "test456";
    String extAcctLocalPart = testName;
    String extAcctName = createExternalAcctEntry(extAcctLocalPart, externalPassword, null);

    Map<String, Object> zimbraDomainAttrs = commonZimbraDomainAttrs();
    // setup auto prov
    // commonZimbraDomainAttrs added only LDAP, add preauth here
    StringUtil.addToMultiMap(zimbraDomainAttrs, Provisioning.A_zimbraAutoProvAuthMech,
            AutoProvAuthMech.PREAUTH.name());
    zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchBase, extDomainDn);
    zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchFilter, "(uid=%u)");
    // setup external LDAP auth
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthMech, AuthMech.ldap.name());
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapURL, "ldap://localhost:389");
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapBindDn, "uid=%u,ou=people," + extDomainDn);
    // setup preauth
    String preAuthKey = PreAuthKey.generateRandomPreAuthKey();
    zimbraDomainAttrs.put(Provisioning.A_zimbraPreAuthKey, preAuthKey);

    Domain zimbraDomain = createZimbraDomain(testName, zimbraDomainAttrs);

    String loginName = extAcctLocalPart + "@" + zimbraDomain.getName();

    // preauth data
    String preAuthUrl = TestPreAuthServlet.genPreAuthUrl(preAuthKey, loginName, false, false);

    // do the preauth servlet request
    String url = TestUtil.getBaseUrl() + preAuthUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    boolean ok = false;
    try {/*  w  w w  . j a v a 2  s .co  m*/
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        ok = (respCode == 200);

        /*
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
                
        System.out.println("Headers");
        Header[] respHeaders = method.getResponseHeaders();
        for (int i=0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        System.out.println(header);
        }
        */

        /*
        String respBody = method.getResponseBodyAsString();
        System.out.println(respBody);
        */

    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }

    assertTrue(ok);

    /*
    String encodedAuthToken = response.getElement(AccountConstants.E_AUTH_TOKEN).getText();
    assertNotNull(encodedAuthToken);
    AuthToken authToken = AuthToken.getAuthToken(encodedAuthToken);
    String acctId = authToken.getAccountId();
    Account acct = prov.get(AccountBy.id, acctId);
    verifyAcctAutoProvisioned(acct, loginName.toLowerCase());
    */
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private void checkStreamStatus(int status, HttpMethod httpMethod) throws HttpClientException {
    LOG.debug(String.format("Got status: %s %s", status, httpMethod.getStatusText()));
    if (status != 200 && status != 201) {
        try {/*from   w ww  .j  av a2  s .  co m*/
            String responseBodyAsString = httpMethod.getResponseBodyAsString();
            if (!StringUtils.isEmpty(responseBodyAsString)) {
                responseBodyAsString = new String(responseBodyAsString.getBytes(), "UTF-8");
                throw new HttpClientException(
                        "Bad status : " + httpMethod.getStatusText() + ":\n" + responseBodyAsString);
            } else {
                throw new HttpClientException("Bad status : " + httpMethod.getStatusLine());
            }
        } catch (Exception e) {
            throw new HttpClientException("Bad status : " + status + ". Could not read response body.");
        }
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse execute(HttpMethod method) throws IOException {
    if (isOauthEnabled) {
        signWithOAuth(method);//from   www.j ava 2  s  . com
    }

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine = null;
    LOG.startTimer(TIMER_NAME);
    try {

        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        method.releaseConnection();
        LOG.stopTimer(TIMER_NAME);
    }
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument search(HashMap<String, String> request)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;
    String urlStr = prepareUrl(request);
    Log.debug("The following search is goint to be executed:" + urlStr);
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }/*w  w w .  j av a 2 s .c o m*/

    return solrResponse;
}

From source file:ait.ffma.service.preservation.riskmanagement.api.PreservationRiskmanagementServiceImpl.java

/**
 * This method tries to establish HTTP connection for passed URI
 * @param uri The URI to verify/*from  w w w  .  ja v  a  2 s  . c om*/
 * @param responseLineList 
 *        This list collects response lines for broken URIs
 * @param brokenUriList
 *        This list collects broken URIs
 */
private void verifyUri(String uri, List<String> responseLineList, List<String> brokenUriList) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    try {
        HttpMethod method = new GetMethod(uri);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        int response = method.getStatusCode();
        if (response != 200) {
            StatusLine responseLine = method.getStatusLine();
            log.info("uri: " + uri + ", response: " + response + ", responseLine: " + responseLine.toString());
            brokenUriList.add(uri);
            responseLineList.add(responseLine.toString());
        }
        method.releaseConnection();
    } catch (IOException e) {
        log.info("Unable to connect to " + uri + " verification error: " + e);
        brokenUriList.add(uri);
        responseLineList.add(e.getMessage());
    }
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument delete(String id)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;

    String urlStr = this.solrHost + "/update?stream.body="
            + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true";

    Log.debug("The " + id + " item is going to be deleted");
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }//from  www . j a v a 2 s  .  co  m

    return solrResponse;
}