URLConnection类的使用

URLConnection类概述

  URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection,它是基于Http协议的。另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。URLConnection通过一个链接获取数据步骤:

  1.URL realUrl = new URL(url); 创建一个指向特定地址的URL实例;

  2.URLConnection connection = realUrl.openConnection(); 创建链接对象

  3.处理设置参数和一般请求属性。

  4.connection.connect(); 与远程资源交互,获取投资段和内容。

参数设置:

  • setAllowUserInteraction 设置此 URLConnection 的 allowUserInteraction 字段的值
  • setDoInput 将此 URLConnection 的 doInput 字段的值设置为指定的值。
  • setDoOutput 将此 URLConnection 的 doOutput 字段的值设置为指定的值。
  • setIfModifiedSince 将此 URLConnection 的 ifModifiedSince 字段的值设置为指定的值。
  • setUseCaches 将此 URLConnection 的 useCaches 字段的值设置为指定的值
  • setConnectTimeout 设置一个指定的超时值(以毫秒为单位),该值将在打开到此 URLConnection 引用的资源的通信链接时使用。
  • setReadTimeout 将读超时设置为指定的超时值,以毫秒为单位。

使用 setDefaultAllowUserInteraction 和 setDefaultUseCaches 可设置 AllowUserInteraction 和 UseCaches 参数的默认值。

设置请求参数:

  • setRequestProperty 设置一般请求属性。
  • addRequestProperty 添加由键值对指定的一般请求属性。

URLConnection的使用

get方式获取数据

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class UrlConnectionTest {
    public static void main(String[] args) {
        String url = "https://www.cnblogs.com/";
        String result = "";
        BufferedReader in = null;
        try {

            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            
            connection.setUseCaches(false);
            connection.setConnectTimeout(5000); //请求超时时间

            //设置通用的请求属性 更多的头字段信息可以查阅HTTP协议
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while((line = in.readLine())!=null){
                result += line + "
";
            }
            Document document = Jsoup.parse(result);

            System.out.println(document);
        }catch (Exception e){
            System.out.println("发送Get请求出现异常!"+e);
        }finally {
            try {
                if(in != null){
                    in.close();
                }
            }catch (Exception e2){
                e2.printStackTrace();
            }
        }
    }
}                

post方式获取数据   //这种方式直接复制的别人代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class PostDemo {

    public static void main(String[] args) {
        try {
            // 1. 获取访问地址URL
            URL url = new URL("http://localhost:8080/Servlet/do_login.do");
            // 2. 创建HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            /* 3. 设置请求参数等 */
            // 请求方式
            connection.setRequestMethod("POST");
            // 超时时间
            connection.setConnectTimeout(3000);
            // 设置是否输出
            connection.setDoOutput(true);
            // 设置是否读入
            connection.setDoInput(true);
            // 设置是否使用缓存
            connection.setUseCaches(false);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置使用标准编码格式编码参数的名-值对
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 连接
            connection.connect();
            /* 4. 处理输入输出 */
            // 写入参数到请求中
            String params = "username=test&password=123456";
            OutputStream out = connection.getOutputStream();
            out.write(params.getBytes());
            out.flush();
            out.close();
            // 从连接中读取响应信息
            String msg = "";
            int code = connection.getResponseCode();
            if (code == 200) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    msg += line + "
";
                }
                reader.close();
            }
            // 5. 断开连接
            connection.disconnect();

            // 处理结果
            System.out.println(msg);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}    

  

  

原文地址:https://www.cnblogs.com/shirandedan/p/8422776.html