· 7 years ago · Mar 11, 2018, 09:34 AM
1public static String postApache(String url) {
2 String dataFormServer = "";
3 String dataToServer="?method=getInfo&nonce=20";
4 String key = "xxx";
5 String secretKey = "yyy";
6 String signedData = calculateHMAC(dataToServer, secretKey);
7 try {
8 CloseableHttpClient client = HttpClients.createDefault();
9 HttpPost httpPost = new HttpPost(url);
10 List<NameValuePair> params = new ArrayList<NameValuePair>(2);
11 params.add(new BasicNameValuePair("Key", key));
12 params.add(new BasicNameValuePair("Sign",signedData));
13
14 httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
15 CloseableHttpResponse response = client.execute(httpPost);
16 HttpEntity entity = response.getEntity();
17 if (entity != null) {
18 dataFormServer = org.apache.commons.io.IOUtils.toString(entity.getContent(), "cp1251");
19 }
20 else System.out.println("Error");
21 } catch (IOException e) {
22 e.printStackTrace();
23 }
24 return dataFormServer;
25 }
26
27private static String calculateHMAC(String data, String key) {
28 SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA512);
29 Mac mac = null;
30 try {
31 mac = Mac.getInstance(HMAC_SHA512);
32 mac.init(secretKeySpec);
33 } catch (NoSuchAlgorithmException e) {
34 e.printStackTrace();
35 } catch (InvalidKeyException e) {
36 e.printStackTrace();
37 }
38 return toHexString(mac.doFinal(data.getBytes()));
39 }
40 private static String toHexString(byte[] bytes) {
41 final char[] hexArray = "0123456789ABCDEF".toCharArray();
42 char[] hexChars = new char[bytes.length * 2];
43 for ( int j = 0; j < bytes.length; j++ ) {
44 int v = bytes[j] & 0xFF;
45 hexChars[j * 2] = hexArray[v >>> 4];
46 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
47 }
48 return new String(hexChars);
49 }