首页 > 解决方案 > 返回的字符串值未显示,JAVA

问题描述

我正在尝试使用 AliExpress API 构建应用程序。但是当我请求 API-URL 使用它时,它返回一个空值。这是我的 FlashActivity 课程。

FlashActivity.class

public class FlashActivity extends AppCompatActivity {

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);


public String urlCreate() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("timestamp", sdf.format(Calendar.getInstance().getTime()));
        paramMap.put("v", "2.0");
        paramMap.put("app_key", "12345");
        paramMap.put("sign_method", "hmac");
        paramMap.put("keywords","household");

        String sign = APISign.signTopRequest(paramMap, "c30839b757nfj45hdfi5545bc994384046f", APISign.SIGN_METHOD_HMAC);
        String getResult = APISign.sendGet(" https://eco.taobao.com/router/rest",
                APISign.buildQuery(paramMap, "UTF-8") + "&sign=" + sign);

        return getResult;

}


private void parseJSON() throws ApiException, IOException {

        String url = urlCreate();

        Log.d(" This is for test-", "Value: " + url);


        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            JSONObject jsonObject = new JSONObject(response.toString());


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);

    }
}

这就是我从Log.d得到的 D/ This is for test-: Value:

我想使用返回的字符串值来使用 volley 解析数据。我是Java新手,我不知道如何解决这个问题。

APISignActivity.class



public class APISign {

    /** MD5 signature */
    private static final String SIGN_METHOD_MD5 = "md5";
    /** HMAC signature */
    public static final String SIGN_METHOD_HMAC = "hmac";
    /** HMAC-SHA256 signature */
    private static final String SIGN_METHOD_HMAC_SHA256 = "hmac-sha256";
    /** UTF-8 Character set **/
    public static final String CHARSET_UTF8 = "UTF-8";


    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            //System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            //connect with URL
            URLConnection connection = realUrl.openConnection();
            //create connection
            connection.connect();
            //define BufferedReader to get response of URL
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            //System.out.println("An exception occurred when sending a GET request!&quot; + e);
            e.printStackTrace();
        }
        //use finally block to close instream
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;

        for (Map.Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            //Ignore parameters whose parameter name or parameter value is empty
            if (areNotEmpty(name, value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }

                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }

        return query.toString();
    }

    /**
     * make signature
     *
     * @param params All character TOP request parameters
     * @param secret signing secret
     * @param signMethod signMethod support:empty(old md5)、md5, hmac_md5
     * @return signature
     */
    public static String signTopRequest(Map<String, String> params, String secret, String signMethod)
            throws IOException {
        //1step:Check if the parameters are sorted
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        //2step:String together all parameter names and parameter values
        StringBuilder query = new StringBuilder();
        if (SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            if (areNotEmpty(key, value)) {
                query.append(key).append(value);
            }
        }

        //3step:Use MD5/HMAC encryption
        byte[] bytes;
        if (SIGN_METHOD_HMAC.equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), secret);
        } else if (SIGN_METHOD_HMAC_SHA256.equals(signMethod)) {
            bytes = encryptHMACSHA256(query.toString(), secret);
        } else {
            query.append(secret);
            bytes = encryptMD5(query.toString());
        }

        //4step:Convert binary to uppercase hexadecimal
        return byte2hex(bytes);
    }

    private static byte[] encryptHMACSHA256(String data, String secret) throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), "HmacSHA256");
            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;
    }

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

    /**
     * After encoding the string with UTF-8, use MD5 for digest
     */

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes(CHARSET_UTF8));
    }

    /**
     * MD5 digest of byte stream
     */

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

    /**
     * Convert byte stream to hexadecimal representation
     */

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


    /**
     * Check if the specified string list is not empty */

    public static boolean areNotEmpty(String... values) {
        boolean result = true;
        if (values == null || values.length == 0) {
            result = false;
        } else {
            for (String value : values) {
                result &= !isEmpty(value);
            }
        }
        return result;
    }


    /**
     * Check whether the specified string is empty
     * <ul>
     * <li>SysUtils.isEmpty(null) = true</li>
     * <li>SysUtils.isEmpty("") = true</li>
     * <li>SysUtils.isEmpty(" ") = true</li>
     * <li>SysUtils.isEmpty("abc") = false</li>
     * </ul>
     *
     * @param value String to be checked
     * @return true/false
     */

    public static boolean isEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
}

标签: javaandroid-studio

解决方案


推荐阅读