Skip to main content
Published: June 02 2011, 6:13:00 PMUpdated: November 28 2020, 9:47:39 PM


 This code illustrates how to use gzip compression in Shopping with straight XML. The API call is fired using Java HttpURLConnection POST.

/*
© 2011-2013 eBay Inc., All Rights Reserved
Licensed under CDDL 1.0 - http://opensource.org/licenses/cddl1.php
*/

import java.io.*;
import java.net.*;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

public class ShoppingXMLCompression {
    public static String serverURL = "http://open.api.ebay.com/shopping?",  appID = "YOUR APPID",  compatLevel = "715",  siteID = "0";


    public static Document request() throws Exception {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuild = factory.newDocumentBuilder();
        File getAccountFile = new File("GetShippingCosts.xml");
        Document getShippingCostsReq = docBuild.parse(getAccountFile);
        Document response = fireApiCall(getShippingCostsReq, "GetShippingCosts");
        return response;
    }

    public static Document getGzipDoc(String contentEncHeader, String contentEncValue, InputStream in) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuild = factory.newDocumentBuilder();
        Document doc = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        System.out.println(" entering getGzipDoc ");
        if (contentEncHeader != null && contentEncValue != null) {
            if (contentEncHeader.compareTo("Content-Encoding") == 0 && contentEncValue.compareTo("gzip") == 0) {
                GZIPInputStream zip = new GZIPInputStream(in);
                byte[] buf = new byte[1024];
                int len;
                while ((len = zip.read(buf)) > 0) {
                    bo.write(buf, 0, len);
                }
                if (bo.size() != 0) {
                    System.out.println("getGzipDoc : ByteArrayOutputStream  size=" + bo.size());
                    doc = docBuild.parse(new ByteArrayInputStream(bo.toByteArray()));
                }
            }
        }
        return doc;
    }

    private static Document fireApiCall(Document apiCall, String callName) {
        boolean isGzip = false;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuild = factory.newDocumentBuilder();
            System.out.println("fireApiCall ==>  : thisServerURL=" + serverURL);
            URL url = new URL(serverURL);
            HttpURLConnection connect;

            connect = (HttpURLConnection) url.openConnection();
            connect.setConnectTimeout(1000);
            addHTTPHeaders(connect, callName);
            connect.setDoInput(true);
            connect.setDoOutput(true);
            connect.setRequestMethod("POST");

            // connect.getContentEncoding();
            Document response = null;
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer tr = tf.newTransformer();
            OutputStream out = connect.getOutputStream();
            Source input = new DOMSource(apiCall);
            Result output = new StreamResult(out);
            tr.transform(input, output);
            out.flush();
            out.close();

            InputStream in = connect.getInputStream();

            //Get the stream into a Document object
            String contentEncHeader = "";
            String contentEncValue = "";
            for (int i = 0;; i++) {
                String headerName = connect.getHeaderFieldKey(i);
                String headerValue = connect.getHeaderField(i);
                if (headerName != null) {
                    if (headerName.compareTo("Content-Encoding") == 0) {
                        contentEncHeader = headerName;
                        contentEncValue = headerValue;
                        response = getGzipDoc(contentEncHeader, contentEncValue, in);
                        System.out.print(contentEncHeader);
                        System.out.println(": " + contentEncValue);
                        isGzip = true;
                        break;
                    }
                }

                  if (headerName == null && headerValue == null) {
                     break;
                 }
            }
                 if (!isGzip) {
                    response = docBuild.parse(in);
                }
            return response;
        } catch (MalformedURLException urle) {
            urle.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private static void addHTTPHeaders(URLConnection connection,
            String callName) {
        // Add the X-EBAY-API-VERSION Header
        connection.addRequestProperty("X-EBAY-API-VERSION", compatLevel);
        // Headers
        connection.addRequestProperty("X-EBAY-API-APP-ID", appID);
        // Add the API call name Header
        connection.addRequestProperty("X-EBAY-API-CALL-NAME", callName);
        // Add the Site Id Header
        connection.addRequestProperty("X-EBAY-API-SITEID", siteID);
        // Add the Content-Type Header
        connection.addRequestProperty("Content-Type", "text/xml");
        // Add the X-EBAY-API-REQUEST-ENCODING Header
        connection.addRequestProperty("X-EBAY-API-REQUEST-ENCODING", "XML");
       // Add the Accept-Encoding Header
       connection.addRequestProperty("Accept-Encoding", "gzip");
    }
      public static void main(String[] args) {
        try {
            NodeList ack = null;
            Document resp = request();
            if (resp != null) {
                ack = resp.getElementsByTagName("Ack");
                if (ack.item(0).getTextContent().compareTo("Failure") == 0) {
                    NodeList shortErrorMsg = resp.getElementsByTagName("ShortMessage");
                    String shorterror = shortErrorMsg.item(0).getTextContent();
                    if (shorterror != null && shorterror.length() > 0) {
                        System.out.println("GetShippingCostsResponse :  shorterror=" + shorterror);
                    }
                }
            } else if (resp != null && ack.item(0).getTextContent().compareTo("Failure") != 0) {
                System.out.println("GetShippingCostsResponse : ack=" + ack.item(0).getTextContent());
            }

        } catch (Exception e) {
            // TODO         }
    }
}

How well did this answer your question?
Answers others found helpful