HTTP之NTML认证

package com.byd.mes2.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * NTML认证
 * @author 
 *-- 查看证书
"C:/Program Files/Java/jre7/bin/keytool" -list -keystore "C:/Program Files/Java/jre7/lib/security/cacerts" -storepass changeit
-- 添加证书
"C:/Program Files/Java/jre7/bin/keytool" -import -alias "FKISHEBYD1A_2021" -keystore FKISHEBYD1A_2021 -file "C:\Users\zhuang.shuangling\Desktop\FKISHEBYD1A\FKISHEBYD1A_2021.cer" -keystore "C:/Program Files/Java/jre7/lib/security/cacerts"
-- 删除证书
"C:/Program Files/Java/jre7/bin/keytool" -delete -keystore "C:/Program Files/Java/jre7/lib/security/cacerts" -alias "FKISHEBYD1A_2021" -storepass changeit
 */
public class HttpNtmlRequest {
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException {
		test();
	}
 
 
	public static void test() throws KeyManagementException, NoSuchAlgorithmException {
 
		String urlStr = "https://test.test.com";
 
		String formData = "";
 
		try {
			urlStr += URLEncoder.encode(formData, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		System.out.println(urlStr);
 
		String domain = ""; // May also be referred as realm
		String userName = "user";
		String password = "password";
		String responseText = null;
		try {
			/** Get请求 */
//			responseText = getAuthenticatedResponse(urlStr, domain, userName, password);
			/** Post请求 */
			responseText = postAuthenticatedResponse(urlStr, domain, userName, password);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("response: " + responseText);
 
	}
 
	private static String getAuthenticatedResponse(final String urlStr, final String domain, final String userName,
			final String password) throws IOException {
 
		StringBuilder response = new StringBuilder();
 
		Authenticator.setDefault(new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(domain + "\\" + userName, password.toCharArray());
			}
		});
		URL urlRequest = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
 
		System.out.println(conn.getContentLengthLong());
		System.out.println(conn.getResponseMessage());
		InputStream stream = conn.getInputStream();
		BufferedReader in = new BufferedReader(new InputStreamReader(stream));
		String str = "";
		while ((str = in.readLine()) != null) {
			response.append(str);
		}
		in.close();
 
		return response.toString();
	}
 
	private static String postAuthenticatedResponse(final String urlStr, final String domain, final String userName,
			final String password) throws IOException, KeyManagementException, NoSuchAlgorithmException {
 
		StringBuilder response = new StringBuilder();
 
		Authenticator.setDefault(new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(domain + "\\" + userName, password.toCharArray());
			}
		});
 
		URL urlRequest = new URL(urlStr);
		
		//创建SSLContext对象,并使用我们指定的信任管理器初始化
		X509TrustManager tm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] xcs, String string)
					throws CertificateException {
			}
 
			public void checkServerTrusted(X509Certificate[] xcs, String string)
					throws CertificateException {
			}
 
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		//jdk1.7默认为TLSv1.0,需要修改为TLSv1.2
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); 
        sslContext.init(null, new TrustManager[] { tm }, null);

        //从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        HttpsURLConnection conn = (HttpsURLConnection) urlRequest.openConnection();
        
        //创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        conn.setSSLSocketFactory(ssf);
		
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
 
		OutputStream out = conn.getOutputStream();
		// 写入请求的字符串
		String obj = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        out.write((obj.toString()).getBytes("UTF-8"));
		out.flush();
		InputStream in = conn.getInputStream();
		// read .....
		System.out.println("Responce Code:    " + conn.getResponseCode());
		System.out.println("Responce Message: " + conn.getResponseMessage());
 
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String str = "";
		while ((str = br.readLine()) != null) {
			response.append(str);
		}
		out.close();
		in.close();
 
		return response.toString();
	}
	
 
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值