java模拟Digest.认证

public static int sendPost(String url, String parameters,String username,String password ,String id) {
		String result = "";
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();// 处理请求参数
		String params = "";// 编码之后的参数
	String ip= "";
	String port= "";
		int resCode = 404;
		try {			
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(new AuthScope(ip, port), // 请求地址 + 端口号
					new UsernamePasswordCredentials(username, password));// 用户名 + 密码 (用于验证)
			HttpClient  httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
			   try {
		            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
		            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
		            httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
			HttpPost postMethod = new HttpPost(url);// 请求详细地址(如:http://192.168.1.105:9000/MotorVehicles)
			//根据不通要求自己添加头
			postMethod.addHeader("User-Identify", id);
			postMethod.addHeader("Content-Type", "application/json");

			StringEntity s = new StringEntity(parameters);// 向后台传的json数据
			s.setContentEncoding("utf-8");// 编码
			postMethod.setEntity(s);
			HttpResponse response = httpclient.execute(postMethod); // 执行POST方法
			resCode = response.getStatusLine().getStatusCode();
			System.out.println("resCode = " + resCode); // 获取响应码
//			System.out.println("result = " + EntityUtils.toString(response.getEntity(), "utf-8")); // 获取响应内容
			String resultfirst = EntityUtils.toString(response.getEntity(), "utf-8");
			logger.info("result = " + resultfirst); // 获取响应内容  
			if(resCode == 401) {
				String a = resultfirst;

                // 组织参数,发起第二次请求
                Header[] headers = response.getHeaders("WWW-Authenticate");
                HeaderElement[] elements = headers[0].getElements();
                String realm = null;
                String qop = null;
                String nonce = null;
                String opaque = null;
                String method = "POST";
                
                String uri = url;
                for (HeaderElement element : elements) {
                    if (element.getName().equals("Digest realm")) {
                        realm = element.getValue();
                    } else if (element.getName().equals("qop")) {
                        qop = element.getValue();
                    } else if (element.getName().equals("nonce")) {
                        nonce = element.getValue();
                    } else if (element.getName().equals("opaque")) {
                        opaque = element.getValue();
                    }
                }
                String a1 = username + ":" + realm + ":" + password;
                String a2 = method + ":" + uri;
                String response1 = null;
                String nc = "00000001";
                String cnonce = "uniview";
                // 获取 Digest 这个字符串
                String backString = response.getFirstHeader("WWW-Authenticate").getValue();
                
                try {
                    response1 = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(a1.getBytes("UTF-8")) + ":" + nonce + ":" + nc
                            + ":" + "uniview" + ":" + qop + ":" + DigestUtils.md5DigestAsHex(a2.getBytes("UTF-8"))).getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    System.out.println("md5加密异常"+e);
                   
                }
                postMethod.addHeader("Authorization", backString + ",username=\"" + username + "\"" + ",realm=\"" + realm + "\""
                        + ",nonce=\"" + nonce + "\"" + ",uri=\"" + uri + "\"" + ",qop=\"" + qop + "\"" + ",nc=\"" + nc + "\""
                        + ",cnonce=\"" + cnonce + "\"" + ",response=\"" + response1 + "\"" + ",opaque=\"" + opaque);

                // 发送第二次请求
                response = httpclient.execute(postMethod);
                resCode = response.getStatusLine().getStatusCode();//获取返回响应码
                System.out.println(resCode);
                if (HttpStatus.SC_OK == resCode) {
                  
                	logger.info("result = " + EntityUtils.toString(response.getEntity(), "utf-8")); // 获取响应内容  
                	return resCode;
                } else {
                   
                  
                }
            } else {
               
            
            }
        } catch (Exception e) {
          System.out.println(e);
        }
		return resCode;
	}	
``
对应 的xml

<dependency>
    		<groupId>commons-codec</groupId>
    		<artifactId>commons-codec</artifactId>
   			 <version>1.10</version>
		</dependency>
		  <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.3.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>elasticsearch-rest-client</artifactId>
                    <groupId>org.elasticsearch.client</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
        <dependency>
            <artifactId>elasticsearch-rest-client</artifactId>
            <groupId>org.elasticsearch.client</groupId>
            <version>6.3.1</version>
        </dependency>

        <dependency>
            <artifactId>elasticsearch</artifactId>
            <groupId>org.elasticsearch</groupId>
            <version>6.3.1</version>
        </dependency>
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,可以通过HttpURLConnection来发送带有Digest Auth的SSE请求。首先需要创建一个HttpURLConnection对象,并设置请求的URL、请求方法、以及请求头中的Authorization字段。Authorization字段需要包含Digest Auth的凭证信息,可以使用Java的MessageDigest类来计算请求消息的摘要值,并将摘要值与用户名、密码等信息一起编码成Base64字符串,然后放入Authorization字段中。以下是示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class SSEWithDigestAuth { public static void main(String[] args) throws IOException, NoSuchAlgorithmException { String username = "your_username"; String password = "your_password"; String url = "your_sse_url"; HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); // Calculate digest MessageDigest md = MessageDigest.getInstance("MD5"); String ha1 = username + ":" + "realm" + ":" + password; byte[] ha1Bytes = md.digest(ha1.getBytes()); String ha2 = "GET" + ":" + url; byte[] ha2Bytes = md.digest(ha2.getBytes()); String response = ha1Bytes.toString() + ":" + "nonce" + ":" + "00000001" + ":" + "cnonce" + ":" + "qop" + ":" + ha2Bytes.toString(); byte[] responseBytes = md.digest(response.getBytes()); String digest = Base64.getEncoder().encodeToString(responseBytes); // Set Authorization header String authHeader = "Digest username=\"" + username + "\", realm=\"realm\", nonce=\"nonce\", uri=\"" + url + "\", qop=auth, nc=00000001, cnonce=\"cnonce\", response=\"" + digest + "\""; connection.setRequestProperty("Authorization", authHeader); // Send request BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 在上面的示例代码中,我们使用了Java的MessageDigest类来计算请求消息的md5摘要值,然后将摘要值与用户名、密码等信息编码成Base64字符串,并放入Authorization字段中。注意,这里只是一个简单的示例,实际使用中需要根据具体的情况进行调整和完善。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值