Java Examples

Java Example for findItemsByKeywords

Sample: Basic Call

Retrieves a set of items based on keywords provided.

Task

You want to search Bonanza for items matching the keywords "The King".

Code

Basic Java code to search for items matching "The King":

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONStringer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.URL;
import java.net.HttpURLConnection;

class FindItemsByKeywords {
    public static void main(String[] args) {
        try {
            String devId = "myDevId";
            String certId = "myCertId";

            URL url = new URL("http://api.bonanza.com/api_requests/standard_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String jsonPayload = new JSONStringer()
                .object()
                    .key("keywords")
                    .value("The King")
                .endObject()
                .toString();


            String requestName = "findItemsByKeywords";
            String toWrite = requestName + "=" + jsonPayload;

            writer.write(toWrite);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success") 
                    && jsonResponse.optJSONObject("findItemsByKeywordsResponse") != null) {

                // Success! Now read more keys from the json object
                JSONArray itemsArray = jsonResponse.optJSONObject("findItemsByKeywordsResponse").optJSONArray("item");

                for (int i = 0; i < itemsArray.length(); i++) {
                    System.out.println(itemsArray.optJSONObject(i).optString("title"));
                    System.out.println(itemsArray.optJSONObject(i).optString("viewItemURL"));
                }
            } else {
                System.out.println(jsonResponse);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Data

jsonPayload's value (JSON):

{"keywords":"The King"}

jsonResponse's value (JSON):

{
    "timestamp":"2009-10-31T14:47:13.000Z",
    "version":"1.0",
    "findItemsByKeywordsResponse":{
        "paginationOutput":{
            "totalEntries":2471394,
            "pageNumber":1,
            "entriesPerPage":20
        },
        "item":[
            {
                "primaryCategory":{
                    "categoryName":"Clothing, Shoes amp; Accessories >> Unisex Clothing, Shoes amp; Accs >> Unisex Adult Clothing >> T-Shirts",
                    "categoryId":155193
                },
                "listingInfo":{
                    "price":9.99,
                    "convertedBuyItNowPrice":9.99,
                    "bestOfferEnabled":"true",
                    "listingType":"FixedPrice",
                    "buyItNowPrice":9.99,
                    "startTime":"2009-10-31T00:09:01.000Z",
                    "lastChangeTime":"2009-10-31T00:09:01.000Z"
                },
                "viewItemURL":"http://www.bonanza.com/booths/tshirt_seller_dev/items/CHESS__THE_KING__LOGO_Royal_Blue_T_SHIRT",
                "location":"CA",
                "title":"CHESS \"THE KING\" LOGO Royal Blue T-SHIRT",
                "sellerInfo":{
                    "feedbackRatingStar":"Blue",
                    "membershipLevel":null,
                    "sellerUserName":"T-Shirt Sellin' Deven",
                    "availableForChat":"false",
                    "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg",
                    "positiveFeedbackPercent":"100"
                },
                "itemId":7410001,
                "storeInfo":{
                    "storeName":"Deven's T-Shirt Shoppe",
                    "storeDiscount":null,
                    "storeURL":"http://www.bonanza.com/booths/tshirt_seller_dev",
                    "storeHasBonanza":"false",
                    "storeItemCount":6
                },
                "shippingInfo":{
                    "shippingServiceCost":2.99,
                    "shippingType":"Flat",
                    "shipToLocations":"US"
                },
                "sellingStatus":{
                    "convertedCurrentPrice":9.99,
                    "sellingState":"Active",
                    "currentPrice":9.99
                },
                "postalCode":"94536",
                "paymentMethod":["Paypal"],
                "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/2889/3800/shirt-chess-king.jpg",
                "globalId":"Bonanza",
                "descriptionBrief":"This shirt is only for KINGS!"
            },
            {
                "primaryCategory":{
                    "categoryName":"Home amp; Garden",
                    "categoryId":11700
                },
                "listingInfo":{
                    "price":10.0,
                    "convertedBuyItNowPrice":10.0,
                    "bestOfferEnabled":"true",
                    "listingType":"FixedPrice",
                    "buyItNowPrice":10.0,
                    "startTime":"2009-10-31T00:04:35.000Z",
                    "lastChangeTime":"2009-10-31T00:04:35.000Z"
                },
                "viewItemURL":"http://www.bonanza.com/booths/â?¦",
                "location":"Bolingbrook, IL",
                "title":"Elvisâ?¦",
                "sellerInfo":{
                    "feedbackRatingStar":"Yellow",
                    "membershipLevel":null,
                    "sellerUserName":"â?¦",
                    "availableForChat":"false",
                    "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg",
                    "positiveFeedbackPercent":"100"
                },
                "itemId":7920002,
                "storeInfo":{
                    "storeName":"â?¦",
                    "storeDiscount":null,
                    "storeURL":"http://www.bonanza.com/booths/â?¦",
                    "storeHasBonanza":"false",
                    "storeItemCount":1
                },
                "shippingInfo":{
                    "shippingServiceCost":0,
                    "shippingType":"Free",
                    "shipToLocations":"US"
                },
                "sellingStatus":{
                    "convertedCurrentPrice":10.0,
                    "sellingState":"Active",
                    "currentPrice":10.0
                },
                "postalCode":"60446",
                "paymentMethod":["MOCC","Paypal"],
                "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/â?¦",
                "globalId":"Bonanza",
                "descriptionBrief":"â?¦"
            },
            â?¦
        ]
    },
    "ack":"Success"
}

Java Example for fetchToken

Sample: User Token Fetching

Code

Java code to fetch a token:

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.URL;
import java.net.HttpURLConnection;

class FetchToken {
    public static void main(String[] args) {
        try {
            String devId = "myDevId";
            String certId = "myCertId";

            URL url = new URL("https://api.bonanza.com/api_requests/secure_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String requestName = "fetchTokenRequest";

            writer.write(requestName);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success") 
                    && jsonResponse.optJSONObject("fetchTokenResponse") != null) {
                // Success! Now read more keys from the json object
                JSONObject fetchTokenJson = jsonResponse.optJSONObject("fetchTokenResponse");

                System.out.println("Your token: " + fetchTokenJson.optString("authToken"));
                System.out.println("Token expiration time: " + fetchTokenJson.optString("hardExpirationTime"));
                System.out.println("Authentication URL: " + fetchTokenJson.optString("authenticationURL"));
            }


        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Data

jsonResponse's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T17:23:15.000Z",
  "fetchTokenResponse":{
    "authToken":"eIJgdkZkMq",
    "hardExpirationTime":"2016-01-14T17:23:15.000Z",
    "authenticationURL":"https://www.bonanza.com/login?apitoken=eIJgdkZkMq"
  }
}

Java Example for getCategories

Sample: Getting Categories

Code

Java code to get information of all children categories of the provided categoryID:

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONStringer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.URL;
import java.net.HttpURLConnection;

class GetCategories {
    public static void main(String[] args) {
        try {
            String devId = "myDevId";
            String certId = "myCertId";

            URL url = new URL("http://api.bonanza.com/api_requests/standard_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String jsonPayload = new JSONStringer()
                .object()
                    .key("categoryParent")
                    .value("2984")
                .endObject()
                .toString();

            String requestName = "GetCategoriesRequest";

            writer.write(requestName + "=" + jsonPayload);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success") 
                    && jsonResponse.optJSONObject("getCategoriesResponse") != null) {
                // Success! Now read more keys from the json object
                JSONArray categoryArray = jsonResponse.optJSONObject("getCategoriesResponse").optJSONArray("categoryArray");
                
                for (int i = 0; i < categoryArray.length(); i++) {
                    JSONObject category = categoryArray.optJSONObject(i);
                    System.out.println(category.optInt("categoryId"));
                    System.out.println(category.optString("categoryName"));
                }
            } else {
                System.out.println(jsonResponse);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Data

jsonResponse's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:47:26.000Z",
  "getCategoriesResponse":{
    "categoryArray":[
      {
        "categoryId":1261,
        "categoryLevel":2,
        "categoryName":"Baby >> Other",
        "leafCategory":"true",
        "categoryBriefName":"Other",
        "traitCount":4
      },
      {
        "categoryId":19068,
        "categoryLevel":2,
        "categoryName":"Baby >> Toys for Baby",
        "leafCategory":"false",
        "categoryBriefName":"Toys for Baby",
        "traitCount":4
      },
      {
        "categoryId":20394,
        "categoryLevel":2,
        "categoryName":"Baby >> Bathing & Grooming",
        "leafCategory":"false",
        "categoryBriefName":"Bathing & Grooming",
        "traitCount":4
      }
    ]
  }
}

Java Example for getOrders

Sample: Getting Orders

Code

Java code to get order information for a seller in a specific time period

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONStringer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.URL;
import java.net.HttpURLConnection;

class GetOrders {
    public static void main(String[] args) {
        try {
            String devId = "myDevId";
            String certId = "myCertId";

            URL url = new URL("http://api.bonanza.com/api_requests/secure_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String jsonPayload = new JSONStringer()
                .object()
                    .key("requesterCredentials")
                    .object()
                        .key("bonanzleAuthToken")
                        .value("myAuthToken")
                    .endObject()
                    .key("orderRole")
                    .value("seller")
                .endObject()
                .toString();

            String requestName = "GetOrdersRequest";

            String toWrite = requestName + "=" + jsonPayload;

            writer.write(toWrite);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success") 
                    && jsonResponse.optJSONObject("getOrdersResponse") != null) {

                // Success! Now read more keys from the json object
                JSONArray orderArray = jsonResponse.optJSONObject("getOrdersResponse").optJSONArray("orderArray");

                for (int i = 0; i < orderArray.length(); i++) {
                    JSONObject order = orderArray.optJSONObject(i).optJSONObject("order");
                    System.out.println("ORDER #" + i + " ======================");
                    System.out.println("Order ID: " + order.optInt("orderID"));
                    System.out.println("Buyer's Username: " + order.optString("buyerUserName"));
                    System.out.println("Amount Paid: " + order.optString("amountPaid"));
                    System.out.println("Creation Time: " + order.optString("createdTime"));
                    System.out.println("Status: " + order.optJSONObject("checkoutStatus").optString("status"));
                }
            } else {
                System.out.println(jsonResponse);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Data

jsonResponse's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:55:25.000Z",
  "getOrdersResponse":{
    "orderArray":[
      {
        "order":{
          "amountPaid":"104.32",
          "amountSaved":0.0,
          "buyerCheckoutMessage":"",
          "buyerUserID":6157,
          "buyerUserName":"JDoe",
          "checkoutStatus":{
            "status":"Complete"
          },
          "createdTime":"2013-04-25T16:54:25Z",
          "creatingUserRole":"Buyer",
          "itemArray":[
            {
              "item":{
                "itemID":205172,
                "sellerInventoryID":null,
                "sku":null,
                "title":"76 Blank DVD Cases",
                "price":"24.0",
                "quantity":1
              }
            }
          ],
          "orderID":1811,
          "orderStatus":"Shipped",
          "subtotal":24.0,
          "taxAmount":0.0,
          "total":"104.32",
          "transactionArray":{
            "transaction":{
              "buyer":{
                "email":"testy@bonanza.com"
              },
            "providerName":"Checkout by Amazon",
            "providerID":"104-1031316-4215451",
            "finalValueFee":"3.3"
            }
          },
          "paidTime":"2013-04-25T17:08:24Z",
          "shippedTime":"2014-04-28T23:19:08Z",
          "shippingAddress":{
            "addressID":6710,
            "cityName":"SEATTLE",
            "country":"US",
            "countryName":null,
            "name":"Test User",
            "postalCode":"98122-90210",
            "stateOrProvince":"WA",
            "street1":null,
            "street2":null
          },
          "shippingDetails":{
            "insuranceFee":0,
            "amount":"81.52",
            "servicesArray":[],
            "shippingService":"Standard shipping"
          }
        }
      }],
    "hasMoreOrders":"false",
    "paginationResult":{
      "totalNumberOfEntries":2,
      "totalNumberOfPages":1
    },
    "pageNumber":1
  }
}

Java Example for addFixedPriceItem

Sample: Adding an Item

Code

Java code to add an item

import org.json.JSONObject;
import org.json.JSONStringer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.URL;
import java.net.HttpURLConnection;

class AddFixedPriceItem {
    public static void main(String[] args) {
        try {
            String devId = "myDevId";
            String certId = "myCertId";

            URL url = new URL("https://api.bonanza.com/api_requests/secure_request");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
            connection.setRequestProperty("X-BONANZLE-API-CERT-NAME", certId);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            String jsonPayload = new JSONStringer()
                .object()
                    .key("requesterCredentials")
                    .object()
                        .key("bonanzleAuthToken")
                        .value("myAuthToken")
                    .endObject()

                    .key("item")
                    .object()
                        .key("title")
                        .value("Lightsaber")

                        .key("primaryCategory")
                        .object()
                            .key("categoryId")
                            .value("163128")
                        .endObject()

                        .key("description")
                        .value("An elegant weapon, for a more civilized age<br>* SELLER <strong>NOT LIABLE</strong> FOR DISMEMBERMENT *")
                        .key("price")
                        .value("42")
                        .key("quantity")
                        .value("3")
                        .key("shippingType")
                        .value("Free")

                        .key("itemSpecifics")
                        .array()
                            .array()
                                .value("condition")
                                .value("used")
                            .endArray()
                            .array()
                                .value("danger")
                                .value("extreme")
                            .endArray()
                        .endArray()

                        .key("pictureDetails")
                        .object()
                            .key("pictureURL")
                            .array()
                                .value("http://images.discountstarwarscostumes.com/products/9284/1-1/luke-skywalker-blue-lightsaber.jpg")
                                .value("http://www.rankopedia.com/CandidatePix/29862.gif")
                            .endArray()
                        .endObject()

                        .key("variations")
                            .array()
                                .object()
                                    .key("quantity")
                                    .value("2")
                                    .key("nameValueList")
                                    .array()
                                        .object()
                                            .key("name")
                                            .value("Colour")
                                            .key("value")
                                            .value("Blue")
                                        .endObject()
                                        .object()
                                            .key("name")
                                            .value("Style")
                                            .key("value")
                                            .value("Single")
                                        .endObject()
                                    .endArray()
                                .endObject()
                                .object()
                                    .key("quantity")
                                    .value("1")
                                    .key("nameValueList")
                                    .array()
                                        .object()
                                            .key("name")
                                            .value("Colour")
                                            .key("value")
                                            .value("Red")
                                        .endObject()
                                        .object()
                                            .key("name")
                                            .value("Style")
                                            .key("value")
                                            .value("Double")
                                        .endObject()
                                    .endArray()
                                .endObject()
                            .endArray()
                    .endObject()
                .endObject()
                .toString();

            String requestName = "addFixedPriceItemRequest";

            String toWrite = requestName + "=" + jsonPayload;

            writer.write(toWrite);
            writer.flush();
            writer.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = in.readLine();

            JSONObject jsonResponse = new JSONObject(response);

            if (jsonResponse.optString("ack").equals("Success") 
                    && jsonResponse.optJSONObject("addFixedPriceItemResponse") != null) {

                // Success! Now read more keys from the json object
                JSONObject outputFields = jsonResponse.optJSONObject("addFixedPriceItemResponse");
                System.out.println("Item ID: " + outputFields.optInt("itemId"));
                System.out.println("Category ID: " + outputFields.optInt("categoryId"));
                System.out.println("Selling State: " + outputFields.optString("sellingState"));
            } else {
                System.out.println(jsonResponse);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Data

jsonResponse's value (JSON [formatted for legibility] ):

{
        "ack":"Success",
        "version":"1.0beta",
        "timestamp":"2015-01-14T17:05:23.000Z",
        "addFixedPriceItemResponse":{
                "itemId":206013,
                "categoryId":163128,
                "sellingState":"Ready for sale",
                "message":null
        }
}