如何发起一个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("
");
        }
        //关闭流
        bufferedReader.close();
        //关闭连接
        connection.disconnect();
        return stringBuilder.toString() ;
    }

}
    使用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;
    }
 
}
经验分享 程序员 微信小程序 职场和发展