• java httpclient的digest验证(可恨,找遍全网没有靠谱的,不是少包就是少文件。含泪整理o(╥﹏╥)o~~~~)


    背景:调用第三方接口,使用的是digest auth鉴权方式,

    basic auth和digest auth比较:

    basic认证是把用户和密码通过base64加密后发送给服务器进行验证。

    Basic认证过程简单,每次请求都有发送密码。安全性较低

    为了解决Basic模式安全问题,HTTP1.1时提出了Digest模式,它的基本原理是把服务器响应的401消息里面的特定的值和用户名以及密码结合起来进行不可逆的摘要算法运算得到一个值,然后把用户名和这个摘要值发给服务器,服务通过用户名去 在自己本地找到对应的密码,然后进行同样的摘要运算,再比较这个值是否和客户端发过来的摘要值一样。

    具体详见此网页描述

    1.先上实体类 BodyRequestConfig 、FormRequestConfig

    1. /**
    2. * 适用于 参数放 请求体的提交可以是JOSN或者XML
    3. */
    4. public class BodyRequestConfig {
    5. /**
    6. * 协议,http或者https
    7. */
    8. private String agreement = "http";
    9. /**
    10. * example 175.13.254.22
    11. */
    12. private String ip;
    13. /**
    14. * 端口
    15. */
    16. private Integer port = 80;
    17. /**
    18. * 账号
    19. * example admin
    20. */
    21. private String username;
    22. /**
    23. * 原密码
    24. * example 123456
    25. */
    26. private String password;
    27. /**
    28. * 除了协议、ip,端口后面的uri
    29. * example /ISAPI/AccessControl/UserInfo/Record?format=json
    30. */
    31. private String uri;
    32. /**
    33. * 请求体 JSON | XML
    34. */
    35. private String entity;
    36. public String getAgreement() {
    37. return agreement;
    38. }
    39. public void setAgreement(String agreement) {
    40. this.agreement = agreement;
    41. }
    42. public String getIp() {
    43. return ip;
    44. }
    45. public void setIp(String ip) {
    46. this.ip = ip;
    47. }
    48. public Integer getPort() {
    49. return port;
    50. }
    51. public void setPort(Integer port) {
    52. this.port = port;
    53. }
    54. public String getUsername() {
    55. return username;
    56. }
    57. public void setUsername(String username) {
    58. this.username = username;
    59. }
    60. public String getPassword() {
    61. return password;
    62. }
    63. public void setPassword(String password) {
    64. this.password = password;
    65. }
    66. public String getUri() {
    67. return uri;
    68. }
    69. public void setUri(String uri) {
    70. this.uri = uri;
    71. }
    72. public String getEntity() {
    73. return entity;
    74. }
    75. public void setEntity(String entity) {
    76. this.entity = entity;
    77. }
    78. }
    1. import java.io.File;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. /**
    5. * 适用于form-data提交
    6. */
    7. public class FormRequestConfig {
    8. /**
    9. * 协议,http或者https
    10. */
    11. private String agreement = "http";
    12. /**
    13. * example 175.13.254.22
    14. */
    15. private String ip;
    16. /**
    17. * 端口
    18. */
    19. private Integer port = 80;
    20. /**
    21. * 账号
    22. * example admin
    23. */
    24. private String username;
    25. /**
    26. * 原密码
    27. * example 123456
    28. */
    29. private String password;
    30. /**
    31. * 除了协议、ip,端口后面的uri
    32. * example /ISAPI/AccessControl/UserInfo/Record?format=json
    33. */
    34. private String uri;
    35. /**
    36. * 请求参数
    37. */
    38. private Map formData = new HashMap<>();
    39. private File file;
    40. /**
    41. * 文件请求的name
    42. */
    43. private String fileName;
    44. /**
    45. * application/json
    46. * text/xml
    47. */
    48. private String type = "application/json";
    49. public String getAgreement() {
    50. return agreement;
    51. }
    52. public void setAgreement(String agreement) {
    53. this.agreement = agreement;
    54. }
    55. public String getIp() {
    56. return ip;
    57. }
    58. public void setIp(String ip) {
    59. this.ip = ip;
    60. }
    61. public Integer getPort() {
    62. return port;
    63. }
    64. public void setPort(Integer port) {
    65. this.port = port;
    66. }
    67. public String getUsername() {
    68. return username;
    69. }
    70. public void setUsername(String username) {
    71. this.username = username;
    72. }
    73. public String getPassword() {
    74. return password;
    75. }
    76. public void setPassword(String password) {
    77. this.password = password;
    78. }
    79. public String getUri() {
    80. return uri;
    81. }
    82. public void setUri(String uri) {
    83. this.uri = uri;
    84. }
    85. public Map getFormData() {
    86. return formData;
    87. }
    88. public File getFile() {
    89. return file;
    90. }
    91. public void setFile(File file) {
    92. this.file = file;
    93. }
    94. public void setFormData(Map formData) {
    95. this.formData = formData;
    96. }
    97. public String getFileName() {
    98. return fileName;
    99. }
    100. public void setFileName(String fileName) {
    101. this.fileName = fileName;
    102. }
    103. public String getType() {
    104. return type;
    105. }
    106. public void setType(String type) {
    107. this.type = type;
    108. }
    109. }

    工具类: HikHttpUtil

    1. import com.hik.entity.BodyRequestConfig;
    2. import com.hik.entity.FormRequestConfig;
    3. import org.apache.http.Consts;
    4. import org.apache.http.HttpEntity;
    5. import org.apache.http.auth.AuthScope;
    6. import org.apache.http.auth.UsernamePasswordCredentials;
    7. import org.apache.http.client.CredentialsProvider;
    8. import org.apache.http.client.methods.*;
    9. import org.apache.http.entity.ContentType;
    10. import org.apache.http.entity.StringEntity;
    11. import org.apache.http.entity.mime.MultipartEntityBuilder;
    12. import org.apache.http.entity.mime.content.StringBody;
    13. import org.apache.http.impl.client.BasicCredentialsProvider;
    14. import org.apache.http.impl.client.CloseableHttpClient;
    15. import org.apache.http.impl.client.HttpClients;
    16. import org.apache.http.util.EntityUtils;
    17. import java.io.FileNotFoundException;
    18. public class HikHttpUtil {
    19. /**
    20. * get请求
    21. * @param config
    22. * @return
    23. * @throws Exception
    24. */
    25. public String doGet(BodyRequestConfig config) throws Exception {
    26. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    27. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    28. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    29. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    30. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    31. HttpGet httpGet = new HttpGet(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    32. CloseableHttpResponse responseBody = httpclient.execute(httpGet);
    33. HttpEntity responseEntity = responseBody.getEntity();
    34. if (responseEntity != null) {
    35. String response = EntityUtils.toString(responseEntity);
    36. return response;
    37. }
    38. return null;
    39. }
    40. /**
    41. * delete请求
    42. * @param config
    43. * @return
    44. * @throws Exception
    45. */
    46. public String doDelete(BodyRequestConfig config) throws Exception {
    47. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    48. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    49. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    50. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    51. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    52. HttpDelete httpDelete = new HttpDelete(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    53. CloseableHttpResponse responseBody = httpclient.execute(httpDelete);
    54. HttpEntity responseEntity = responseBody.getEntity();
    55. if (responseEntity != null) {
    56. String response = EntityUtils.toString(responseEntity);
    57. return response;
    58. }
    59. return null;
    60. }
    61. /**
    62. * body方式发起post请求
    63. * @param config
    64. * @return
    65. * @throws Exception
    66. */
    67. public String doBodyPost(BodyRequestConfig config) throws Exception {
    68. String entity = config.getEntity();
    69. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    70. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    71. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    72. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    73. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    74. HttpPost httpPost = new HttpPost(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    75. httpPost.setEntity(new StringEntity(entity, "UTF-8"));
    76. CloseableHttpResponse responseBody = httpclient.execute(httpPost);
    77. HttpEntity responseEntity = responseBody.getEntity();
    78. if (responseEntity != null) {
    79. String response = EntityUtils.toString(responseEntity);
    80. return response;
    81. }
    82. return null;
    83. }
    84. /**
    85. * body方式发起post请求
    86. * @param config
    87. * @return
    88. * @throws Exception
    89. */
    90. public String doBodyPut(BodyRequestConfig config) throws Exception {
    91. String entity = config.getEntity();
    92. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    93. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    94. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    95. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    96. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    97. HttpPut HttpPut = new HttpPut(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    98. HttpPut.setEntity(new StringEntity(entity, "UTF-8"));
    99. CloseableHttpResponse responseBody = httpclient.execute(HttpPut);
    100. HttpEntity responseEntity = responseBody.getEntity();
    101. if (responseEntity != null) {
    102. String response = EntityUtils.toString(responseEntity);
    103. return response;
    104. }
    105. return null;
    106. }
    107. /**
    108. * 以表单方式发起 post 请求
    109. * @param config
    110. * @return
    111. * @throws Exception
    112. */
    113. public String doFormDataPost(FormRequestConfig config) throws Exception {
    114. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    115. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    116. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    117. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    118. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    119. HttpPost httpPost = new HttpPost(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    120. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    121. config.getFormData().forEach((k,v)->{
    122. builder.addPart(k,new StringBody(v, ContentType.create(config.getType(), Consts.UTF_8)));
    123. });
    124. if (config.getFile()!=null){
    125. if (!config.getFile().exists()){
    126. throw new FileNotFoundException("文件不存在!"+config.getFile().getAbsolutePath());
    127. }
    128. builder.addBinaryBody(config.getFileName(),config.getFile(),ContentType.create("image/jpeg"),config.getFile().getName());
    129. }
    130. HttpEntity reqEntity = builder.build();
    131. httpPost.setEntity(reqEntity);
    132. CloseableHttpResponse responseBody = httpclient.execute(httpPost);
    133. HttpEntity responseEntity = responseBody.getEntity();
    134. if (responseEntity != null) {
    135. String response = EntityUtils.toString(responseEntity);
    136. return response;
    137. }
    138. return null;
    139. }
    140. /**
    141. * 表单方式发起 put 请求
    142. * @param config
    143. * @return
    144. * @throws Exception
    145. */
    146. public String doFormDataPut(FormRequestConfig config) throws Exception {
    147. CredentialsProvider credsProvider = new BasicCredentialsProvider();
    148. AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
    149. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
    150. credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
    151. CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    152. HttpPut httpPut = new HttpPut(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
    153. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    154. config.getFormData().forEach((k,v)->{
    155. builder.addPart(k,new StringBody(v, ContentType.create(config.getType(), Consts.UTF_8)));
    156. });
    157. if (config.getFile()!=null){
    158. if (!config.getFile().exists()){
    159. throw new FileNotFoundException("文件不存在!"+config.getFile().getAbsolutePath());
    160. }
    161. builder.addBinaryBody(config.getFileName(),config.getFile(),ContentType.create("image/jpeg"),config.getFile().getName());
    162. }
    163. HttpEntity reqEntity = builder.build();
    164. httpPut.setEntity(reqEntity);
    165. CloseableHttpResponse responseBody = httpclient.execute(httpPut);
    166. HttpEntity responseEntity = responseBody.getEntity();
    167. if (responseEntity != null) {
    168. String response = EntityUtils.toString(responseEntity);
    169. return response;
    170. }
    171. return null;
    172. }
    173. }

     pom.xml文件 

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>com.hikgroupId>
    7. <artifactId>ISAPIUtilartifactId>
    8. <version>1.0version>
    9. <properties>
    10. <maven.compiler.source>8maven.compiler.source>
    11. <maven.compiler.target>8maven.compiler.target>
    12. properties>
    13. <dependencies>
    14. <dependency>
    15. <groupId>org.apache.httpcomponentsgroupId>
    16. <artifactId>httpclientartifactId>
    17. <version>4.5version>
    18. dependency>
    19. <dependency>
    20. <groupId>org.apache.httpcomponentsgroupId>
    21. <artifactId>httpmimeartifactId>
    22. <version>4.5version>
    23. dependency>
    24. <dependency>
    25. <groupId>org.apache.httpcomponentsgroupId>
    26. <artifactId>httpcoreartifactId>
    27. <version>4.4.1version>
    28. dependency>
    29. dependencies>
    30. project>

    测试案例:

    1. import com.hik.HikHttpUtil;
    2. import com.hik.entity.BodyRequestConfig;
    3. import com.hik.entity.FormRequestConfig;
    4. import java.io.File;
    5. public class Test {
    6. HikHttpUtil hik = new HikHttpUtil();
    7. public static void main(String[] args) throws Exception {
    8. Test test = new Test();
    9. test.doFormDataPut();
    10. }
    11. public void doFormDataPut() throws Exception {
    12. FormRequestConfig config = new FormRequestConfig();
    13. config.setIp("");
    14. config.setUsername("admin");
    15. config.setPassword("12345");
    16. config.setUri("/ISAPI/Intelligent/FDLib/FDSetUp?format=json");
    17. config.setFileName("img");
    18. config.setFile(new File("C:\\Users\\faceImgs\\01.jpg"));
    19. config.getFormData().put("FaceDataRecord","{\"faceLibType\":\"blackFD\",\"FDID\":\"1\",\"FPID\":\"qiang\"}");
    20. String put = hik.doFormDataPut(config);
    21. System.out.println(put);
    22. }
    23. public void doFormDataPost() throws Exception {
    24. FormRequestConfig config = new FormRequestConfig();
    25. config.setIp("");
    26. config.setUsername("admin");
    27. config.setPassword("12345");
    28. config.setUri("/ISAPI/Intelligent/FDLib/1/picture?type=concurrent");
    29. config.setFileName("importImage");
    30. config.setFile(new File("C:\\Users\\Desktop\\测试图片及文档\\faceImgs\\01.jpg"));
    31. config.getFormData().put("FaceAppendData","001");
    32. String post = hik.doFormDataPost(config);
    33. System.out.println(post);
    34. }
    35. public void doBodyPost(String[] args) throws Exception{
    36. BodyRequestConfig config = new BodyRequestConfig();
    37. config.setIp("");
    38. config.setUsername("admin");
    39. config.setPassword("12345");
    40. config.setUri("/ISAPI/AccessControl/UserInfo/Search?format=json");
    41. config.setEntity("{\n" +
    42. " \"UserInfoSearchCond\":{\n" +
    43. " \"searchID\":\"20200706 19:17:03\",\n" +
    44. " \"searchResultPosition\":0,\n" +
    45. " \"maxResults\":30\n" +
    46. " }\n" +
    47. "}");
    48. String post = hik.doBodyPost(config);
    49. System.out.println(post);
    50. }
    51. public void doBodyPut(String[] args) throws Exception{
    52. BodyRequestConfig config = new BodyRequestConfig();
    53. config.setIp("10.17.35.41");
    54. config.setUsername("admin");
    55. config.setPassword("hik12345");
    56. config.setUri("/ISAPI/AccessControl/UserInfo/Delete?format=json");
    57. config.setEntity("{\n" +
    58. " \"UserInfoDelCond\": {\n" +
    59. " \"EmployeeNoList\": [\n" +
    60. " {\n" +
    61. " \"employeeNo\": \"111\"\n" +
    62. " }\n" +
    63. " ]\n" +
    64. " }\n" +
    65. "}");
    66. String put = hik.doBodyPut(config);
    67. System.out.println(put);
    68. }
    69. public void doGet(String[] args) throws Exception{
    70. BodyRequestConfig config = new BodyRequestConfig();
    71. config.setIp("");
    72. config.setUsername("admin");
    73. config.setPassword("12345");
    74. config.setUri("/ISAPI/Intelligent/FDLib/manualModeling?range=unmodeled&FDID=1");
    75. String get = hik.doGet(config);
    76. System.out.println(get);
    77. }
    78. public void doDelete(String[] args) throws Exception{
    79. BodyRequestConfig config = new BodyRequestConfig();
    80. config.setIp("");
    81. config.setUsername("admin");
    82. config.setPassword("12345");
    83. config.setUri("/ISAPI/Intelligent/FDLib/1/picture/5");
    84. String delete = hik.doDelete(config);
    85. System.out.println(delete);
    86. }
    87. }

    postMan请求第三方接口示例:


     

  • 相关阅读:
    DES加密算法是怎么实现的?
    Python 处理 PDF 的神器 -- PyMuPDF
    Netty源码阅读(1)之——客户端源码梗概
    Python题库(含答案)
    JavaScript 处理数组函数的总结
    Koa全栈登录鉴权
    5.k8s jenkins集成k8s一键发布案例
    Rust开发——变量、静态变量与常量
    node-rsa公钥私钥加密解密
    LeetCode每日一题——2652. Sum Multiples
  • 原文地址:https://blog.csdn.net/qq_43511677/article/details/128144206