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:scoap3withapi.Scoap3withAPI.java

public static int getNumRec(String publickey, String privatekey, String date, int jrec, int num_rec) {

    HttpClient client = new HttpClient();
    HttpMethod method = callAPISCOAP3(publickey, privatekey, date, jrec, num_rec);

    double numRec = 0;
    int numFor = 0;
    String responseXML = null;/* w w  w. j  a va  2  s  .c om*/
    BufferedReader br = null;
    try {
        client.executeMethod(method);
    } catch (IOException ex) {
        Logger.getLogger(Scoap3withAPI.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (method.getStatusCode() == HttpStatus.SC_OK) {
        try {
            method.getResponseBody();

            responseXML = convertStreamToString(method.getResponseBodyAsStream());

            System.out.println("RESPONSE XML " + responseXML);
            numRec = Double.parseDouble(responseXML.split("Results:")[1].split("-->")[0].replace(" ", ""));

            System.out.println("NUM REC=>" + numRec / 100);

            numFor = (int) Math.ceil(numRec / 100);

            System.out.println("NUM REC=>" + numFor);

            method.releaseConnection();

        } catch (IOException ex) {
            Logger.getLogger(Scoap3withAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    return numFor;
}

From source file:scoap3withapi.Scoap3withAPI.java

public static void writeFilesScoap3(String publickey, String privatekey, String date, int jrec, int num_rec) {
    String responseXML = null;//from   w  w  w .  ja  v  a2s .c  om
    HttpClient client = new HttpClient();
    HttpMethod method = callAPISCOAP3(publickey, privatekey, date, jrec, num_rec);

    try {
        client.executeMethod(method);

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

            responseXML = convertStreamToString(method.getResponseBodyAsStream());

            FileWriter fw = new FileWriter("MARCXML_SCOAP3_from_" + startDate + "_to_" + todayDate
                    + "/marcXML_scoap3_" + jrec + "_" + num_rec + ".xml");

            fw.append(responseXML);

            fw.close();

        }
    } catch (IOException e) {
        e.printStackTrace();

    } finally {

        method.releaseConnection();

    }

}

From source file:smartrics.rest.client.RestClientImpl.java

/**
 * See {@link smartrics.rest.client.RestClient#execute(java.lang.String, smartrics.rest.client.RestRequest)}
 *//* ww  w . ja  v a  2 s . c  om*/
public RestResponse execute(String hostAddr, final RestRequest request) {
    if (request == null || !request.isValid())
        throw new IllegalArgumentException("Invalid request " + request);
    if (request.getTransactionId() == null)
        request.setTransactionId(Long.valueOf(System.currentTimeMillis()));
    LOG.debug("request: {}", request);
    HttpMethod m = createHttpClientMethod(request);
    configureHttpMethod(m, hostAddr, request);
    RestResponse resp = new RestResponse();
    resp.setTransactionId(request.getTransactionId());
    resp.setResource(request.getResource());
    try {
        client.executeMethod(m);
        for (Header h : m.getResponseHeaders()) {
            resp.addHeader(h.getName(), h.getValue());
        }
        resp.setStatusCode(m.getStatusCode());
        resp.setStatusText(m.getStatusText());
        resp.setBody(m.getResponseBodyAsString());
        resp.setRawBody(m.getResponseBody());
    } catch (HttpException e) {
        String message = "Http call failed for protocol failure";
        throw new IllegalStateException(message, e);
    } catch (IOException e) {
        String message = "Http call failed for IO failure";
        throw new IllegalStateException(message, e);
    } finally {
        m.releaseConnection();
    }
    LOG.debug("response: {}", resp);
    return resp;
}

From source file:smilehouse.opensyncro.defaultcomponents.http.HTTPUtils.java

/**
 * Makes a HTTP request to the specified url with a set of parameters,
  * request method, user name and password
 * //from w  ww  .  j  a v  a  2s  . c o  m
 * @param url the <code>URL</code> to make a request to 
 * @param method either "GET", "POST", "PUT" or "SOAP"
 * @param parameters two dimensional string array containing parameters to send in the request
 * @param user user name to submit in the request 
 * @param password password to submit in the request
 * @param charsetName charset name used for message content encoding
  * @param responseCharsetName charset name used to decode HTTP responses,
  *                            or null to use default ("ISO-8859-1")
  * @param contentType Content-Type header value (without charset information)
  *                    for POST (and SOAP) type requests. If null, defaults to
  *                    "text/xml".
 * @return a string array containing the body of the response, the headers of
  *         the response and possible error message
 * @throws Exception 
 */
public static HTTPResponse makeRequest(URL url, String method, String[][] parameters, String user,
        String password, String charsetName, String responseCharsetName, String contentType) throws Exception {

    HttpClient httpclient = new HttpClient();

    HttpMethod request_method = null;
    HTTPResponse responseData = new HTTPResponse();
    NameValuePair[] names_values = null;

    String requestContentType;
    if (contentType != null && contentType.length() > 0) {
        requestContentType = contentType;
    } else {
        requestContentType = DEFAULT_CONTENT_TYPE;
    }

    if (parameters != null && method.equals("PUT") == false) {
        names_values = new NameValuePair[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            names_values[i] = new NameValuePair(parameters[i][0], parameters[i][1]);
        }

    }
    if (method.equalsIgnoreCase("POST")) {
        request_method = new PostMethod(url.toString());
        if (names_values != null)
            ((PostMethod) request_method).setRequestBody(names_values);
    } else if (method.equalsIgnoreCase("PUT")) {
        if (parameters == null)
            throw new Exception("No data to use in PUT request");
        request_method = new PutMethod(url.toString());
        StringRequestEntity sre = new StringRequestEntity(parameters[0][0]);
        ((PutMethod) request_method).setRequestEntity(sre);
    } else if (method.equalsIgnoreCase("SOAP")) {
        String urlString = url.toString() + "?";
        String message = null;
        String action = null;
        for (int i = 0; i < parameters.length; i++) {

            if (parameters[i][0].equals(SOAPMESSAGE))
                message = parameters[i][1];
            else if (parameters[i][0].equals(SOAP_ACTION_HEADER))
                action = parameters[i][1];
            else
                urlString += parameters[i][0] + "=" + parameters[i][1] + "&";
        }
        urlString = urlString.substring(0, urlString.length() - 1);
        request_method = new PostMethod(urlString);
        // Encoding content with requested charset 
        StringRequestEntity sre = new StringRequestEntity(message, requestContentType, charsetName);
        ((PostMethod) request_method).setRequestEntity(sre);
        if (action != null) {
            request_method.setRequestHeader(SOAP_ACTION_HEADER, action);
        }
        // Adding charset also into header's Content-Type
        request_method.addRequestHeader(CONTENT_TYPE_HEADER, requestContentType + "; charset=" + charsetName);
    } else {
        request_method = new GetMethod(url.toString());
        if (names_values != null)
            ((GetMethod) request_method).setQueryString(names_values);
    }

    user = (user == null || user.length() < 1) ? null : user;
    password = (password == null || password.length() < 1) ? null : password;

    if ((user != null & password == null) || (user == null & password != null)) {
        throw new Exception("Invalid username or password");

    }
    if (user != null && password != null) {
        httpclient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
        httpclient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);
        request_method.setDoAuthentication(true);
    }

    try {
        httpclient.executeMethod(request_method);

        if (request_method.getStatusCode() != HttpStatus.SC_OK) {
            responseData
                    .setResponseError(request_method.getStatusCode() + " " + request_method.getStatusText());
        }

        //Write response header to the out string array
        Header[] headers = request_method.getResponseHeaders();
        responseData.appendToHeaders("\nHTTP status " + request_method.getStatusCode() + "\n");
        for (int i = 0; i < headers.length; i++) {
            responseData.appendToHeaders(headers[i].getName() + ": " + headers[i].getValue() + "\n");
        }

        /*
         * TODO: By default, the response charset should be read from the Content-Type header of 
         * the response and that should be used in the InputStreamReader constructor: 
         * 
         * <code>new InputStreamReader(request_method.getResponseBodyAsStream(), 
         *                   ((HttpMethodBase)request_method).getResponseCharSet());</code>
         * 
         * But for backwards compatibility, the charset used by default is now the one that the 
         * HttpClient library chooses (ISO-8859-1). An alternative charset can be chosen, but in 
         * no situation is the charset read from the response's Content-Type header.
         */
        BufferedReader br = null;
        if (responseCharsetName != null) {
            br = new BufferedReader(
                    new InputStreamReader(request_method.getResponseBodyAsStream(), responseCharsetName));
        } else {
            br = new BufferedReader(new InputStreamReader(request_method.getResponseBodyAsStream()));
        }

        String responseline;
        //Write response body to the out string array
        while ((responseline = br.readLine()) != null) {
            responseData.appendToBody(responseline + "\n");
        }
    } finally {
        request_method.releaseConnection();
    }
    return responseData;
}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Runs a WEBDAV command/*from  w  w  w . ja v a2  s  .  c o m*/
 * @param client The HTTP client transport to use
 * @param method The method to be executed
 * @return True/False based on execution
 * @throws IOException
 */
public static boolean executeMethod(HttpClient client, HttpMethod method) throws IOException {
    client.executeMethod(method);
    int statusCode = method.getStatusCode();
    logger.trace("executeMethod - statusCode - " + statusCode);

    boolean result = method.getStatusCode() == HttpURLConnection.HTTP_OK;
    logger.debug("executeMethod - result - " + result);
    logger.debug(method.getStatusCode() + " " + method.getStatusText() + " " + method.getResponseBodyAsString()
            + " " + Arrays.toString(method.getResponseHeaders()));

    return result;
}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Used for checking if a file exists//from  www. j a v  a  2  s . c  o  m
 * @param client    The client to execute the method
 * @param method    The method to be executed
 * @param ignoreHTTPNOTFOUND  Used to flag if the HTTP_NOT_FOUND error has to be ignored, if not the IOException raised will be thrown
 * @return  Returns if the execution has been successful
 * @throws IOException
 */
public static boolean executeMethod(HttpClient client, HttpMethod method, boolean ignoreHTTPNOTFOUND)
        throws IOException {
    try {
        client.executeMethod(method);
    } catch (IOException e) {
        //If it is not 404 - throw exception, otherwise
        if (method.getStatusCode() != HttpURLConnection.HTTP_NOT_FOUND)
            throw e;
    }
    int statusCode = method.getStatusCode();
    logger.trace("executeMethod - statusCode - " + statusCode);

    boolean result = (method.getStatusCode() == HttpURLConnection.HTTP_OK);
    logger.debug("executeMethod - result - " + result);
    logger.debug(method.getStatusCode() + " " + method.getStatusText() + " " + method.getResponseBodyAsString()
            + " " + Arrays.toString(method.getResponseHeaders()));

    return result;
}

From source file:uk.org.openeyes.oink.facade.ITFacadeRoute.java

@Test
@DirtiesContext/*from w  w w  .  j  a v a 2s .c  om*/
public void testSimplePatientGet() throws Exception {

    /*
     * Set up Third Party Service
     */

    // Specify what the third party service should receive
    IncomingMessageVerifier v = new IncomingMessageVerifier() {
        @Override
        public void isValid(OINKRequestMessage incoming) {
            Assert.assertEquals(uk.org.openeyes.oink.domain.HttpMethod.GET, incoming.getMethod());
            Assert.assertEquals("/Patient/2342452", incoming.getResourcePath());
            Assert.assertNull(incoming.getBody());
        }
    };

    // Specify what the third party service should return
    OINKResponseMessage mockResponse = new OINKResponseMessage();
    mockResponse.setStatus(200);
    mockResponse.setBody(buildFhirBodyFromResource("/example-messages/fhir/patient.json"));

    // Start the third party service
    SimulatedThirdParty thirdp = new SimulatedThirdParty(v, mockResponse);
    thirdp.start();

    /*
     * Make REST request
     */

    // Prepare request
    HttpClient client = new HttpClient();

    HttpMethod method = new GetMethod(testProperties.getProperty("facade.uri") + "/Patient/2342452");

    client.executeMethod(method);
    thirdp.close();

    /*
     * Process REST response
     */
    byte[] responseBody = method.getResponseBody();
    String responseJson = new String(responseBody);
    int responseCode = method.getStatusCode();
    String responseContentType = method.getResponseHeader("Content-Type").getValue();
    method.releaseConnection();

    if (thirdPartyAssertionError != null) {
        throw thirdPartyAssertionError;
    }

    Assert.assertEquals(HttpStatus.SC_OK, responseCode);
    Assert.assertEquals("application/json+fhir", responseContentType);
    Assert.assertEquals(IOUtils.toString(
            this.getClass().getResourceAsStream("/example-messages/fhir/patient.json"), "UTF-8"), responseJson);
}

From source file:wuit.common.crawler.WebSit.CrawlerAPIBaiDu.java

/**
  * HTTP GET?HTML/*from   www.j av  a 2s.  co m*/
  *
  * @param url
  *            URL?
  * @param queryString
  *            ?,?null
  * @param charset
  *            
  * @param pretty
  *            ?
  * @return ?HTML
  */
public static String doGet(String url, String queryString, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        if (StringUtils.isNotBlank(queryString))
            // get??http?????%?
            method.setQueryString(URIUtil.encodeQuery(queryString));
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty)
                    response.append(line).append(System.getProperty("line.separator"));
                else
                    response.append(line);
            }
            reader.close();
        }
    } catch (URIException e) {
        log.error("HTTP Get?" + queryString + "???", e);
    } catch (IOException ex) {
        Logger.getLogger(CrawlerAPIBaiDu.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}