• 如何发起一个HTTP请求,发送HTTP请求的几种方式


    概述

    如何发起一个HTTP请求?这个问题似乎既简单又复杂,简单是指当你在浏览器里输入一个URL时,按回车键后这个HTTP请求就发起了,很快你就会看到这个请求的返回结果。复杂是指能否不借助浏览器也能发起请求,不借助有两层含义:

    • 能不能自己组装一个符合HTTP协议,
    • 处理浏览器还有哪些方式也能简单地发起一个HTTP请求

    如何发起一个HTTP请求

    如何发起和如何建立一个Socket连接区别不大,只不过outputStream.write写的二进制字节数据格式要符合HTTP协议。浏览器在建立socket连接之前,必须根据地址栏输入的URL的域名DNS解析出IP地址,在根据这个IP地址和默认80端口与远程服务器建立Socket连接,然后浏览器根据这个URL组装成一个get类型的HTTP请求头,通过outputStream.write 发送到目标,服务器等待inputStream.read返回数据,最后断开这个连接

    模拟浏览器发送HTTP请求方式

    使用原生HttpURLConnection

    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    
    public class HttpClientTest {
    
    
        public static String doGet(String httpUrl) throws IOException {
            URL url = null ;
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("GET");
            //设置超时时间
            connection.setReadTimeout(1000);
            //创立连接
            connection.connect();
    
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            
            StringBuilder stringBuilder = new StringBuilder();
            while (bufferedReader.readLine()!=null){
                stringBuilder.append(bufferedReader.readLine());
                stringBuilder.append("\r\n");
            }
            //关闭流
            bufferedReader.close();
            //关闭连接
            connection.disconnect();
            return stringBuilder.toString() ;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 使用HttpClient工具
    public class HttpClientTest1 {
        /**
         * Get请求
         *
         * @param httpUrl
         * @return
         * @throws IOException
         */
        public static String doGet(String httpUrl) throws IOException {
            //1.创建httpClient,httpGet对象 2.配置请求信息 3.执行get请求,通过httpEntity对象得到返回数据 4.字符转换
            //5.关闭资源
            String result;
            //两种创建client的方法,这里是使用了CloseableHttpClient这个实现类,相当于已经废弃的defaultHttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(httpUrl);
            //根据实际配置,这里是默认配置,超时设置连接设置什么的都是通过RequestConfig对象配置的
            httpGet.setConfig(RequestConfig.DEFAULT);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            httpResponse.close();
            return result;
     
        }
     
        /**
         * Post请求
         *
         * @param httpUrl
         * @param param
         * @return
         * @throws IOException
         */
        public static String doPost(String httpUrl, String param) throws IOException {
            //1.创建httpClient,httpPost对象 2.配置请求信息 3.执行post请求 4.获得httpEntity,进行字符转换 5.关闭资源
            String result;
            //这里使用HttpClient创建client,使用面向接口编程
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost();
            httpPost.setConfig(RequestConfig.DEFAULT);
            httpPost.setEntity(new StringEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            return result;
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
  • 相关阅读:
    java计算机毕业设计ssm贫困区教育资源捐赠平台element vue前后端分离
    ElasticSearch--优化写入速度的方法--单个索引的操作
    <数据结构>停车场管理系统,利用栈和队列实现,包含纯c语言版和C++版的全注释源码
    【ASTGCN】代码解读(torch)之train_ASTGCN_r(二)
    使用stream下载文件避坑-》堆内存溢出的原因
    linux Nginx+Tomcat负载均衡、动静分离
    软考 系统架构设计师系列知识点之数字孪生体(2)
    spring boot 项目中的application不能执行是什么问题
    springBoot集成mongo相关常用基础和复杂操作
    Chiplet:大算力的翅膀
  • 原文地址:https://blog.csdn.net/weixin_54046648/article/details/127646020