public static void main(String[] args) {
try {
// params 请求参数
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);
}
// 获取请求body长度
int contentlength = queryString.getBytes().length;
// 接口校验账户信息
String api_key = "10000";
String api_pass = "poiuytrewq1234567890";
// 请求的接口
String url = "http://127.0.0.1/api/2/login.dhtml";
// 请求事件
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());
// 将请求事件和请求签名添加到header当中
Map<String, String> headers = new HashMap<String, String>();
headers.put("date", date + "");
headers.put("sign", api_key + ":" + md5Sign);
// 封装http body请求体
HttpRequestBody body = new HttpRequestBody(url, charSet, HttpMethod.POST, headers, null, params);
HttpClient client = new HttpClient();
HttpResponseBody response = client.service(body);
// http请求返回状态
System.out.println(response.getCode());
// http请求返回结果
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();
}
}
服务端获取后校验