import android.text.TextUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by Administrator on 2017/8/14.
*/
public class TbkRequest {
private static final int TIMEOUT = 5 * 1000;
private static final String SIGN_METHOD_MD5 = "md5";
private static final String SIGN_METHOD_HMAC = "hmac";
private static final String CHARSET_UTF8 = "utf-8";
private static final String CONTENT_ENCODING_GZIP = "gzip";
public static final String serverUrl = "http://gw.api.taobao.com/router/rest";
public static final String appKey = "";
public static final String appSecret = "";
public static void HttpClientGet(String url,
RequestParams params, RequestCallBack callBack) {
HttpUtils utils = new HttpUtils(TIMEOUT);
// utils.configCurrentHttpCacheExpiry(0);
if (params == null)
params = new RequestParams();
// utils.configDefaultHttpCacheExpiry(0);
utils.send(HttpRequest.HttpMethod.GET, url, params, callBack);
}
public static void HttpClientPost(final String url, RequestParams params, RequestCallBack callBack) {
HttpUtils utils = new HttpUtils(TIMEOUT);
utils.send(HttpRequest.HttpMethod.POST, url, params, callBack);
}
public static final String SALES = "total_sales_des";
public static final String PRICE = "zk_final_price_asc";//不可用 需要解析后排序
public static final String PRICE_DES = "zk_final_price_dec";
public static void recommend(String key, String sort, int page, RequestCallBack callBack) {
Map map = new HashMap();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
map.put("timestamp", df.format(new Date()));
map.put("v", "2.0");
map.put("app_key", appKey);
map.put("target_app_key", appSecret);
map.put("method", "taobao.tbk.item.get");
map.put("format", "json");
// map.put("cat", "16,18");
if (!TextUtils.isEmpty(sort)) {
map.put("sort", sort);
}
map.put("page_no", page + "");
map.put("q", key);
map.put("force_sensitive_param_fuzzy", "true");
map.put("fields", "num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
map.put("sign_method", SIGN_METHOD_MD5);
RequestParams params = new RequestParams();
for (Map.Entry entry : map.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
params.addQueryStringParameter(name, value);
}
}
String sign = null;
try {
sign = signTopRequest(map, appSecret, SIGN_METHOD_MD5);
} catch (IOException e) {
e.printStackTrace();
}
params.addQueryStringParameter("sign", sign);
HttpClientGet(serverUrl, params, callBack);
}
// http://gw.api.taobao.com/router/rest?sign=E3F878389140607D9603E9C350762A17×tamp=2017-08-16 14:28:52&v=2.0&app_key=24580132&method=taobao.tbk.uatm.favorites.item.get&partner_id=top-apitools&format=json&adzone_id=126536537&favorites_id=10087023&force_sensitive_param_fuzzy=true&fields=num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick
public static void favorites(long adzone_id, long favorites_id, int page, RequestCallBack callBack) {
Map map = new HashMap();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
map.put("timestamp", df.format(new Date()));
map.put("v", "2.0");
map.put("app_key", appKey);
map.put("target_app_key", appSecret);
map.put("method", "taobao.tbk.uatm.favorites.item.get");
map.put("format", "json");
map.put("force_sensitive_param_fuzzy", "true");
map.put("fields", "num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
map.put("sign_method", SIGN_METHOD_MD5);
// long adzone_id = 126536537;
// long favorites_id = 10087023;
map.put("adzone_id", adzone_id + "");
map.put("favorites_id", favorites_id + "");
map.put("page_no", page + "");
RequestParams params = new RequestParams();
for (Map.Entry entry : map.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
params.addQueryStringParameter(name, value);
}
}
String sign = null;
try {
sign = signTopRequest(map, appSecret, SIGN_METHOD_MD5);
} catch (IOException e) {
e.printStackTrace();
}
params.addQueryStringParameter("sign", sign);
HttpClientGet(serverUrl, params, callBack);
}
/**
* 对TOP请求进行签名。
*/
private static String signTopRequest(Map params, String secret, String signMethod) throws IOException {
// 第一步:检查参数是否已经排序
String[] keys = params.keySet().toArray(new String[0]);
Arrays.sort(keys);
// 第二步:把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder();
if (SIGN_METHOD_MD5.equals(signMethod)) {
query.append(secret);
}
for (String key : keys) {
String value = params.get(key);
if (isNotEmpty(key) && isNotEmpty(value)) {
query.append(key).append(value);
}
}
// 第三步:使用MD5/HMAC加密
byte[] bytes;
if (SIGN_METHOD_HMAC.equals(signMethod)) {
bytes = encryptHMAC(query.toString(), secret);
} else {
query.append(secret);
bytes = encryptMD5(query.toString());
}
// 第四步:把二进制转化为大写的十六进制
return byte2hex(bytes);
}
/**
* 对字节流进行HMAC_MD5摘要。
*/
private static byte[] encryptHMAC(String data, String secret) throws IOException {
byte[] bytes = null;
try {
SecretKey secretKey = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), "HmacMD5");
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
bytes = mac.doFinal(data.getBytes(CHARSET_UTF8));
} catch (GeneralSecurityException gse) {
throw new IOException(gse.toString());
}
return bytes;
}
/**
* 对字符串采用UTF-8编码后,用MD5进行摘要。
*/
private static byte[] encryptMD5(String data) throws IOException {
return encryptMD5(data.getBytes(CHARSET_UTF8));
}
/**
* 对字节流进行MD5摘要。
*/
private static byte[] encryptMD5(byte[] data) throws IOException {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
bytes = md.digest(data);
} catch (GeneralSecurityException gse) {
throw new IOException(gse.toString());
}
return bytes;
}
/**
* 把字节流转换为十六进制表示方式。
*/
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
private static String callApi(URL url, Map params) throws IOException {
String query = buildQuery(params, CHARSET_UTF8);
byte[] content = {};
if (query != null) {
content = query.getBytes(CHARSET_UTF8);
}
HttpURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Host", url.getHost());
conn.setRequestProperty("Accept", "text/xml,text/javascript");
conn.setRequestProperty("User-Agent", "top-sdk-java");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHARSET_UTF8);
out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
} finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static String buildQuery(Map params, String charset) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set> entries = params.entrySet();
boolean hasParam = false;
for (Entry entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
// 忽略参数名或参数值为空的参数
if (isNotEmpty(name) && isNotEmpty(value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
}
private static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
if (conn.getResponseCode() < 400) {
String contentEncoding = conn.getContentEncoding();
if (CONTENT_ENCODING_GZIP.equalsIgnoreCase(contentEncoding)) {
return getStreamAsString(new GZIPInputStream(conn.getInputStream()), charset);
} else {
return getStreamAsString(conn.getInputStream(), charset);
}
} else {// Client Error 4xx and Server Error 5xx
throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
Reader reader = new InputStreamReader(stream, charset);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = CHARSET_UTF8;
if (isNotEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (isNotEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
private static boolean isNotEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return false;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(value.charAt(i)) == false)) {
return true;
}
}
return false;
}
}