static public Response send()

in ch-sxmp/src/main/java/com/cloudhopper/sxmp/SxmpSender.java [77:138]


    static public Response send(String url, Request request, boolean shouldParseResponse) throws UnsupportedEncodingException, SxmpErrorException, IOException, SxmpParsingException, SAXException, ParserConfigurationException {
        // convert request into xml
        String requestXml = SxmpWriter.createString(request);
        String responseXml = null;

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

        long start = System.currentTimeMillis();
        long stop = 0;

        logger.debug("Request XML:\n" + requestXml);

        // execute request
        try {
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(requestXml);
            // write old or new encoding?
            if (request.getVersion().equals(SxmpParser.VERSION_1_1)) {
                // v1.1 is utf-8
                entity.setContentType("text/xml; charset=\"utf-8\"");
            } else {
                // v1.0 was 8859-1, though that's technically wrong
                // unspecified XML must be encoded in UTF-8
                // maintained this way for backward compatibility
                entity.setContentType("text/xml; charset=\"iso-8859-1\"");
            }
            post.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            // execute request (will throw exception if fails)
            responseXml = client.execute(post, responseHandler);

            stop = System.currentTimeMillis();
        } finally {
            // clean up all resources
            client.getConnectionManager().shutdown();
        }

        logger.debug("Response XML:\n" + responseXml);
        logger.debug("Response Time: " + (stop - start) + " ms");

        // deliver responses sometimes aren't parseable since its acceptable
        // for delivery responses to merely return "OK" and an HTTP 200 error
        if (!shouldParseResponse) {
            return null;
        } else {
            // convert response xml into an object
            SxmpParser parser = new SxmpParser(SxmpParser.VERSION_1_0);
            // v1.0 data remains in ISO-8859-1, and responses are v1.0
            ByteArrayInputStream bais = new ByteArrayInputStream(responseXml.getBytes("ISO-8859-1"));
            Operation op = parser.parse(bais);

            if (!(op instanceof Response)) {
                throw new SxmpErrorException(SxmpErrorCode.OPTYPE_MISMATCH, "Unexpected response class type parsed");
            }

            return (Response)op;
        }
    }