HttpURLConnection安全认证式访问方法

 在使用http访问网站时,有时候网站需要提供用户名和密码,才能访问到具体内容。我们用代码怎么来填入这些认证信息呢?

    下面是一些具体的代码:

    URL realUrl = new URL(url);

 

    HttpURLConnection httpUrlConnection = (HttpURLConnection) realUrl.openConnection();        

    httpUrlConnection.setRequestProperty("accept", "*/*");

    httpUrlConnection.setRequestProperty("connection", "Keep-Alive");

    httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;               Windows NT 5.1;SV1)");

    httpUrlConnection.setRequestProperty("content-Type", "text/xml");

    httpUrlConnection.setConnectTimeout(60000);

    //设置用户名和密码

    String user = "www.test.com";

    String pwd = "mysys";

    String auth = user+":"+pwd;

    //对其进行加密

     byte[] rel = Base64.encodeBase64(auth.getBytes());

    String res = new String(rel);

    //设置认证属性

    httpUrlConnection.setRequestProperty("Authorization","Basic " + res);

    httpUrlConnection.setReadTimeout(readTimeout);

    httpUrlConnection.connect();

    Map<String, List<String>> map = httpUrlConnection.getHeaderFields();

 

`HttpURLConnection`是Java提供的一种用于创建HTTP连接并执行GET、POST等HTTP请求的内置类。它是一个低级别的API,主要用于处理HTTP协议,并允许开发者直接操作socket通信。以下是使用`HttpURLConnection`进行网络访问的基本步骤: 1. 创建URL对象,代表你要访问的网络地址。 ```java URL url = new URL("http://example.com/api"); ``` 2. 使用`HttpURLConnection`打开连接,并指定GET或POST等方法。 ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 或者 "POST", "PUT", "DELETE" 等 ``` 3. 设置请求头和所需的权限(如认证信息)。 ```java connection.setRequestProperty("User-Agent", "YourApp/1.0"); if (username != null && password != null) { String auth = username + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuth)); } ``` 4. 发送请求并获取响应状态码和输入流。 ```java int responseCode = connection.getResponseCode(); InputStream inputStream = connection.getInputStream(); ``` 5. 根据响应状态码处理结果(比如解析JSON数据)。 ```java BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } // 关闭资源 reader.close(); inputStream.close(); connection.disconnect(); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值