Welcome Guest. Sign in or Signup

1 Answers

Java sample: use gzip compression in Shopping API XML call

Asked by: 337 views Programming

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

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()));
                }
      &