1、在pom引入一些架包
<!-- 以前的同事使用,感觉还挺好用-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
<!-- 不确定是否使用,有时间再验证-->
<dependency>
<groupId>org.jumpmind.symmetric</groupId>
<artifactId>symmetric-csv</artifactId>
<version>3.5.19</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
2、http连接
2.1、以前的同事使用的,感觉挺好用的便记录下来,架包要先引进来
注意:Accept可为 application/json、text/plain。这里指的是服务器返回给我们数据类型,拉库存返回的Text所以要使用text/plain。要不然会报 406 not accept able!
import java.util.UUID;
String uuid = UUID.randomUUID().toString();//java自带的UUID
String token = "XXXXXXXX";
String site = "xx";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(baseUrl).get().addHeader("Accept", "text/plain")
.addHeader("WM_SVC.NAME", "Walmart Marketplace").addHeader("WM_MARKET", site)
.addHeader("WM_SEC.ACCESS_TOKEN", token)
.addHeader("Authorization", "Basic " + encodeIdAndKey(customerId, privateKey))
.addHeader("WM_QOS.CORRELATION_ID", uuid).build();
try {
Response response = client.newCall(request).execute();
if (response.code() == 200) {
String body = response.body().string();
List<PlatformInventoryDto> inventoryList = buildInventory(
accountSite.getPlatformAccountName(), accountSite.getPlatformName(), siteName,
warehouseName, body);
boolean insertUpdateResult = platformInventoryUtilService.insertUpdate(inventoryList);
if (!insertUpdateResult) {
log.info("inventory {} false " , accountSite.getPlatformAccountName());
}
} else {
log.info("get WalmartWFSInventory error ,code : {} ,msg: {}", response.code(),
response.message());
// response.code()
}
} catch (IOException e) {
// e.printStackTrace();
log.error("WalmartWFSInventory error {} ", e.getMessage());
}
2.2、直接使用java的写法
直接上代码
public String getToken(String cid, String key , String site) {
String url1 = "xxxxxxxxxxxx";
String uuid = UUID.randomUUID().toString();
HttpURLConnection connection = null;
URL url = null;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = null;
String strRead = null;
ObjectMapper mapper = new ObjectMapper();
String accessToken = null;
try {
url = new URL(url1);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(20 * 1000);
connection.setReadTimeout(20 * 1000);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("WM_SVC.NAME", "Walmart Marketplace");
connection.setRequestProperty("WM_MARKET", site);
connection.setRequestProperty("Authorization", "Basic " + encodeIdAndKey(cid, key));
connection.setRequestProperty("WM_QOS.CORRELATION_ID", uuid);
connection.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("grant_type=client_credentials");
writer.flush();
System.out.println(connection.getResponseCode());
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sbf = new StringBuffer();
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
Map<String, String> resMap = null;
resMap = mapper.readValue(result, new TypeReference<Map<String, String>>() {
});
accessToken = resMap.get("access_token");
} catch (IOException e) {
//logger.error(e.getMessage(), e);
}
return accessToken;
}
3、读取CSV文件
private List<PlatformInventoryDto> buildInventory(String accountName,String platformName,
String siteName,String warehouseName,String inventoryCSV) {
List<PlatformInventoryDto> inventoryList = new ArrayList<PlatformInventoryDto>(100);
Map<String,PlatformInventoryDto> inventoryMap = new HashMap<>();
if(inventoryCSV == null) {
return null;
}
//如果是文件,这里修改成FileInputStream
ByteArrayInputStream ais = new ByteArrayInputStream(inventoryCSV.getBytes());
InputStreamReader isr = new InputStreamReader(ais);
CSVReader reader = new CSVReader(isr);
List<String[]> lines = new ArrayList<>();
try {
lines = reader.readAll();
} catch (IOException e) {
//e.printStackTrace();
log.error(e.getMessage());
}
Date confirmDate = new Date();
PlatformInventoryDto inventory = null;
int lineIndex = 1;
for (String[] line : lines) {
if(lineIndex <= 1) {
lineIndex++;
continue;
}
String sellerSku = line[2];
String qty = line[6];
Integer qtyTemp = new Integer(qty);
if(inventoryMap.containsKey(sellerSku)) {
//Integer qtyPre = inventory.getQtySiteSku();
inventory.setQtySiteSku(inventory.getQtySiteSku() + qtyTemp );
} else {
inventory = new PlatformInventoryDto();
inventoryList.add(inventory);
inventory.setSiteSku(sellerSku);
inventory.setQtySiteSku(qtyTemp);
inventory.setAccountName(accountName);
inventory.setPlatformName(platformName);
inventory.setSiteName(siteName);
inventory.setWarehouse(warehouseName);
//站点SKU在平台上的ID
//asin = stock.getSku();
//inventory.setPlatformSkuId(asin);
inventory.setConfirmDate(confirmDate);
}
}
return inventoryList;
}
4、 Base64生成
直接使用java的转换一下
public String encodeIdAndKey(String cid, String key) {
Base64.Encoder encoder = Base64.getEncoder();
String text = cid + ":" + key;
byte[] apiKeyByte = null;
String encodedText = null;
try {
apiKeyByte = text.getBytes("UTF-8");
encodedText = encoder.encodeToString(apiKeyByte);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
return encodedText;
}
5、 406 Not acceptable报错解决
注意:Accept可为 application/json、text/plain。这里指的是服务器返回给我们数据类型,拉库存返回的Text所以要使用text/plain。要不然会报 406 not accept able!
还是要单独出来,毕竟有可能这就是跨不过的槛。