API請(qǐng)求簽名加密,備注

public static void main(String[] args) {
try {
// params 請(qǐng)求參數(shù)
Map<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("password", "test");

        String queryString = "";

        for (Map.Entry<String, String> entry : params.entrySet()) {
            queryString += "&" + entry.getKey() + "=" + entry.getValue();
        }
        if (queryString.length() > 0) {
            queryString = queryString.substring(1);
        }

        // 獲取請(qǐng)求body長(zhǎng)度
        int contentlength = queryString.getBytes().length;
        // 接口校驗(yàn)賬戶信息
        String api_key = "10000";
        String api_pass = "poiuytrewq1234567890";

        // 請(qǐng)求的接口
        String url = "http://127.0.0.1/api/2/login.dhtml";
        // 請(qǐng)求事件
        long date = System.currentTimeMillis();
        // 生成簽名
        StringBuffer sign = new StringBuffer();
        sign.append(HttpMethod.POST);
        sign.append(url);
        sign.append(date);
        sign.append(contentlength);
        sign.append(api_pass);
        String md5Sign = MD5.toMD5(sign.toString());
        // 將請(qǐng)求事件和請(qǐng)求簽名添加到header當(dāng)中
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("date", date + "");
        headers.put("sign", api_key + ":" + md5Sign);
        // 封裝http body請(qǐng)求體
        HttpRequestBody body = new HttpRequestBody(url, charSet, HttpMethod.POST, headers, null, params);
        HttpClient client = new HttpClient();
        HttpResponseBody response = client.service(body);
        // http請(qǐng)求返回狀態(tài)
        System.out.println(response.getCode());
        // http請(qǐng)求返回結(jié)果
        System.out.println(response.getResultString());
    } catch (HttpErrorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

服務(wù)端獲取后校驗(yàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容