java访问http和https的方法(+需要用户名密码 认证的网站)

本文介绍如何使用Java标准库中的URL类及HttpClient库访问HTTP和HTTPS网站,并展示了需要认证的网站访问方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 通过url进行访问

/**
 * 使用URL类进行访问http和https
 */
public class URLTest {
	public static void main(String[] args) {
//		String https2="https://www.apiopen.top/journalismApi";
		String https="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&code=code&grant_type=authorization_code";
		InputStream in=null;
		try {
			URL url=new URL(https);
			HttpsURLConnection openConnection = (HttpsURLConnection) url.openConnection();
			String protocol = url.getProtocol();
			System.out.println(protocol);
			openConnection.connect();
  			in = openConnection.getInputStream();
  			
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

访问结果:

https
{"errcode":41004,"errmsg":"appsecret missing, hints: [ req_id: ODkxIA06672030 ]"}

2 通过httpClient进行访问

/**
 * 使用HttpClient来访问https和http
 * 注意:url地址中不能有null格,不然会报错
 */
public class HttpsTest {
	public static void main(String[] args) {
		CloseableHttpClient client = HttpClients.createDefault();
		String url="https://www.apiopen.top/journalismApi";
		HttpGet get=new HttpGet(url);
		try {
			CloseableHttpResponse execute = client.execute(get);
			HttpEntity entity = execute.getEntity();
			InputStream in = entity.getContent();
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder.toString());
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

 

使用httpclient的pom依赖:

	    <dependency>
	 		<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>

3 不删除null格会报错

4 httpClient链接需要用户名,密码认证的网站

package com.cww.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
 * 使用HttpClient来访问https和http(有的网页需要用户名和密码登录)
 * 注意:url地址中不能有null格,不然会报错
 */
public class HttpsTest {
	public static void main(String[] args) {
		CloseableHttpClient client = HttpClients.createDefault();
		String url="http://localhost:8161/admin/";
//		String url3="https://www.apiopen.top/journalismApi";
//		String url2="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&code=code&grant_type=authorization_code";
		HttpGet get=new HttpGet(url);
		ProtocolVersion protocolVersion = get.getProtocolVersion();
		System.out.println(protocolVersion.getProtocol());
		try {
			//该网页需要认证(用户名、密码)
			HttpClientContext context=new HttpClientContext();
			CredentialsProvider credentialsProvider=new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
			context.setCredentialsProvider(credentialsProvider);
			CloseableHttpResponse execute = client.execute(get, context);
			//----以下一样
			HttpEntity entity = execute.getEntity();
			InputStream in = entity.getContent();
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder.toString());
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

 

### Java 实现自动登录网站的方式 #### 背景说明 在 Web 应用开发中,自动登录是一种常见的用户体验优化手段。它允许用户无需每次访问时重新输入用户名密码即可进入系统。这种功能通常依赖于 **Cookie 技术** 来存储用户的认证信息。 --- #### 自动登录的核心原理 自动登录主要分为两个部分: 1. **保存用户凭证**:当用户选择“记住我”或“自动登录”选项时,在服务器端创建一个包含用户名加密后的密码的 Cookie,并将其发送至客户端浏览器。 2. **验证用户身份**:下次用户访问时,服务器会读取该 Cookie 的内容,解析其中的信息并与数据库中的数据对比,从而决定是否允许用户直接登录。 这一过程的具体实现可以参考以下代码片段: --- #### 后台 Servlet 中的实现逻辑 以下是基于 `Servlet` `JSP` 的典型实现方法: ```java // 判断请求参数是否存在自动登录标志 String autoLoginParam = request.getParameter("autoLogin"); if ("on".equals(autoLoginParam)) { // 创建一个新的 Cookie 对象来保存用户名密码 User user = (User) session.getAttribute("currentUser"); if (user != null) { String usernameAndPassword = user.getUsername() + "#" + encryptPassword(user.getPassword()); Cookie loginCookie = new Cookie("autoLogin", usernameAndPassword); loginCookie.setMaxAge(60 * 60 * 24 * 7); // 设置有效期为一周 loginCookie.setPath("/"); response.addCookie(loginCookie); // 将 Cookie 添加到响应头中 } } ``` 上述代码实现了将用户名经过加密处理的密码存入名为 `autoLogin` 的 Cookie 中[^1]。 --- #### 验证用户名密码的有效性 为了确保安全性,必须对用户名密码进行严格的校验。例如,可以通过正则表达式检查其格式是否合法: ```java public static boolean validateUsername(String username) { return Pattern.matches("\\d{6,10}", username); // 用户名仅限 6 至 10 位数字 } public static boolean validatePassword(String password) { return Pattern.matches("[\\w]{6}", password); // 密码长度固定为 6 位字符 } ``` 如果检测到非法输入,则抛出自定义异常以便进一步处理[^2]。 --- #### 处理 Cookie 数据的安全措施 由于敏感信息可能被恶意攻击者窃取,因此建议采取额外保护机制,比如使用哈希算法对原始密码加盐后再存储。下面是一个简单的例子展示如何安全地编码密码字符串: ```java private String encryptPassword(String rawPassword) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] hashBytes = md.digest((rawPassword + "saltValue").getBytes(StandardCharsets.UTF_8)); StringBuilder hexString = new StringBuilder(); for (byte b : hashBytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); // 返回 SHA-256 哈希值作为最终结果 } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } } ``` 此函数利用了单向散列函数(如 SHA-256),即使泄露也不会轻易还原出真实密码[^3]。 --- #### 客户端行为分析与注意事项 每当用户再次打开网页时,服务端需尝试从 HTTP 请求头部提取已有的 Cookies 并逐一匹配目标键名 `"autoLogin"` 。一旦找到对应项即启动后续的身份确认流程;反之提示重新填写表单项完成手动登陆操作。 需要注意的是,尽管本文描述的技术方案简单易懂,但在实际项目部署前还需综合考虑更多因素诸如 HTTPS 加密传输通道启用与否以及定期清理过期记录等内容以免造成不必要的安全隐患。 --- ### 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值