Java示例

addfixedpriceItem的Java示例

示例:添加项目

代码

java代码添加项目

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("//api.sanyili.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 = "AddFixedPriceItem.Request";

            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("AddFixedPriceItem.Response") != null) {

                // Success! Now read more keys from the json object
                JSONObject outputFields = jsonResponse.optJSONObject("AddFixedPriceItem.Response");
                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);
        }
    }
}

数据

jsonresponse.'值(JSON [格式化可识别]):

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

fetchtoken的Java示例

示例:用户令牌获取

代码

java代码来获取令牌:

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("//api.sanyili.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 = "fetchtoken.Request";

            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("fetchtoken.Response") != null) {
                // Success! Now read more keys from the json object
                JSONObject fetchTokenJson = jsonResponse.optJSONObject("fetchtoken.Response");

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

数据

jsonresponse.'值(JSON [格式化可识别]):

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

findItemsbykeyKeys的Java示例

示例:基本呼叫

根据提供的关键字检索一组项目。

任务

您想搜索Bonanza的商品与关键字“King”匹配。

代码

用于搜索匹配“KING”的物品的基本Java代码:

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("//api.sanyili.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("findItemsbyKeywords.Response") != null) {

                // Success! Now read more keys from the json object
                JSONArray itemsArray = jsonResponse.optJSONObject("findItemsbyKeywords.Response").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);
        }
    }
}

数据

jsonpayload.价值(JSON):

{"keywords":"The King"}

jsonresponse.价值(JSON):

{
    "timestamp":"2009-10-31T14:47:13.000Z",
    "version":"1.0",
    "findItemsbyKeywords.Response":{
        "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.sanyili.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.sanyili.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.sanyili.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.sanyili.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"
}

Get类别的Java示例

样本:获取类别

代码

java代码获取提供的CompountID的所有子类别的信息:

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("//api.sanyili.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("get类别Response") != null) {
                // Success! Now read more keys from the json object
                JSONArray categoryArray = jsonResponse.optJSONObject("get类别Response").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);
        }
    }
}

数据

jsonresponse.'值(JSON [格式化可识别]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:47:26.000Z",
  "get类别Response":{
    "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 for getorders

样品:获取订单

代码

Java代码在特定时间段内获得卖家的订单信息

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("//api.sanyili.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("使是Response") != null) {

                // Success! Now read more keys from the json object
                JSONArray orderArray = jsonResponse.optJSONObject("使是Response").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);
        }
    }
}

数据

jsonresponse.'值(JSON [格式化可识别]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:55:25.000Z",
  "使是Response":{
    "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
  }
}

SetNotificationPreferences的Java示例

示例:设置通知首选项

代码

Java代码指定要侦听卖家反馈/问题事件的URL:

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 javax.net.ssl.HttpsURLConnection;

class SetNotificationPreferences {
    public static void main(String[] args) {
        try {
            String devId = "your_dev_id";
            String certId = "your_cert_id";
            URL url = new URL("//api.sanyili.com/api_requests/secure_request");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "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("setnotificationPreferences.Request")

                    .object()
                        .key("requesterCredentials")
                        .object()
                            .key("bonanzleAuthToken")
                            .value("your_token")
                        .endObject()

                        .key("applicationDeliveryPreferences")
                        .object()
                            .key("applicationEnable")
                            .value("Enable")

                            .key("deliveryURLDetails")
                            .object()
                                .key("deliveryURL")
                                .value("foo.com/notifications")

                                .key("status")
                                .value("Enable")
                            .endObject()
                        .endObject()

                        .key("userDeliveryPreferenceArray")
                        .object()
                            .key("notificationEnable")
                            .array()
                                .object()
                                    .key("eventEnable")
                                    .value("Enable")

                                    .key("eventType")
                                    .value("askSellerQuestion")
                                .endObject()
                                .object()
                                    .key("eventEnable")
                                    .value("Enable")

                                    .key("eventType")
                                    .value("feedback")
                                .endObject()
                            .endArray()
                        .endObject()
                    .endObject()
                .endObject()
                .toString();

            writer.write(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("SetNotificationPreferencesResponse") != null) {
                System.out.println("Success");
                System.out.println(jsonResponse);
            } else {
                System.out.println("Failure");
                System.out.println(jsonResponse);
            }

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

数据

jsonresponse.'值(格式化可易见):

{
        "ack":"Success",
        "version":"1.0",
        "timestamp":"2018-02-20T02:03:16.000Z",
        "setnotificationPreferences.Response":{
                "eventsProcessed":2,
                "deliveryURLsProcessed":1,
                "notificationId":69438
        }
}