import java基础教程传值 org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.UUID;
String serviceUrl = "SERVICE_URL"; // 具体服务的调用地址 int timeout = 500; // 服务调用延时 String clientId = "YOUR_CLIENT_ID"; // 替换为用户的client_id String timestamp = String.valueOf(Instant.now().toEpochMilli()); String nonce = UUID.randomUUID().toString(); String secret = "YOUR_CLIENT_SECRET"; // 替换为用户的client_secret String stringToSign = clientId + timestramp + nonce;
String sign = null; try { Mac hmacSha256 = Mac.getInstance("HmacSHA256"); byte[] keyBytes = secret.getBytes("UTF-8"); hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256")); sign = Base64.encodeBase64String(hmacSha256.doFinal(stringToSign.getBytes("UTF-8"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } catch (InvalidKeyException e) { }
HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); CloseableHttpClient httpClient = httpClientBuilder.build();
HttpPost requestMethod = new HttpPost(); // 根据服务的具体请求方法构造合适的请求方法对象,此处以POST方法为例说明 requestMethod.setURI(serviceUrl); RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build(); requestMethod.setConfig(config);
requestMethod.addHeader("X-Client-Id", clientId); requestMethod.addHeader("X-Timestamp", timestamp); requestMethod.addHeader("X-Nonce", nonce); requestMethod.addHeader("X-Signature", sign);
CloseableHttpResponse response = httpClient.execute(requestMethod);
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/h6javajc/9545.html