java原生发送http请求

简介: java原生发送http请求

根据技术选型总结常见的三种方式发送http请求,本问介绍jdk原生方式,其他两种如下链接

httpclient和okhttp

Springboot整合RestTemplate发送http请求

使用JDK原生提供的net包下的HttpURLConnection、URLConnection、Socket三个类都可实现,无需其他jar包

1、HttpURLConnection类实现

HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。

请求过程

GET:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、发起请求
6、获取请求数据
7、关闭连接
 
POST:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
7、设置传入参数的格式:(setRequestProperty)
8、设置鉴权信息:Authorization:(setRequestProperty)
9、设置参数
10、发起请求
11、获取请求数据
12、关闭连接

代码

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import org.springframework.lang.Nullable;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
 
public class HttpURLConnectionUtil {
 
    /**
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, @Nullable String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
 
            //拼装参数
            if (null != param && param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    public static void main(String[] args) {
        String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
        System.out.println(message);
    }
}

2、URLConnection类实现

package uRLConnection;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
 
public class URLConnectionHelper {
 
    public static String sendRequest(String urlParam) {
 
        URLConnection con = null;  
 
        BufferedReader buffer = null; 
        StringBuffer resultBuffer = null;  
 
        try {
             URL url = new URL(urlParam); 
             con = url.openConnection();  
 
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            return resultBuffer.toString();
 
        }catch(Exception e) {
            e.printStackTrace();
        }
 
        return "";
    }
    public static void main(String[] args) {
        String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
        System.out.println(sendRequest(url));
    }
}

3、Socket类实现

package socket;
import java.io.BufferedInputStream;  
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.net.Socket;  
import java.net.URLEncoder;  
 
import javax.net.ssl.SSLSocket;  
import javax.net.ssl.SSLSocketFactory;  
 
public class SocketForHttpTest {  
 
    private int port;  
    private String host;  
    private Socket socket;  
    private BufferedReader bufferedReader;  
    private BufferedWriter bufferedWriter;  
 
    public SocketForHttpTest(String host,int port) throws Exception{  
 
        this.host = host;  
        this.port = port;  
 
        /**  
         * http协议  
         */  
        // socket = new Socket(this.host, this.port);  
 
        /**  
         * https协议  
         */  
        socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);  
 
 
    }  
 
    public void sendGet() throws IOException{  
        //String requestUrlPath = "/z69183787/article/details/17580325";  
        String requestUrlPath = "/";          
 
        OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());    
        bufferedWriter = new BufferedWriter(streamWriter);              
        bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");    
        bufferedWriter.write("Host: " + this.host + "\r\n");    
        bufferedWriter.write("\r\n");    
        bufferedWriter.flush();    
 
        BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
        bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
        String line = null;    
        while((line = bufferedReader.readLine())!= null){    
            System.out.println(line);    
        }    
        bufferedReader.close();    
        bufferedWriter.close();    
        socket.close();  
 
    }  
 
 
    public void sendPost() throws IOException{    
            String path = "/";    
            String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("张三", "utf-8") + "&" +    
                        URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");    
            // String data = "name=zhigang_jia";    
            System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);              
            OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");    
            bufferedWriter = new BufferedWriter(streamWriter);                  
            bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");    
            bufferedWriter.write("Host: " + this.host + "\r\n");    
            bufferedWriter.write("Content-Length: " + data.length() + "\r\n");    
            bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");    
            bufferedWriter.write("\r\n");    
            bufferedWriter.write(data);    
 
            bufferedWriter.write("\r\n");    
            bufferedWriter.flush();    
 
            BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
            bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
            String line = null;    
            while((line = bufferedReader.readLine())!= null)    
            {    
                System.out.println(line);    
            }    
            bufferedReader.close();    
            bufferedWriter.close();    
            socket.close();    
    }    
 
    public static void main(String[] args) throws Exception {  
        /**  
         * http协议测试  
         */  
        //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);  
        /**  
         * https协议测试  
         */  
        SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);  
        try {  
            forHttpTest.sendGet();  
        //  forHttpTest.sendPost();  
        } catch (IOException e) {  
 
            e.printStackTrace();  
        }  
    }  
 
}  


相关文章
|
11天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 客户端 HTTP 请求 3
该教程展示了如何在Servlet中处理客户端HTTP请求,特别是获取HTTP头信息。示例代码创建了一个名为`DisplayHeader`的Servlet,它扩展了`HttpServlet`并重写了`doGet`方法。在`doGet`中,使用`HttpServletRequest`的`getHeaderNames()`遍历所有头部,显示其名称和对应值。Servlet在TomcatTest项目下,通过`web.xml`配置映射到`/TomcatTest/DisplayHeader`路径。
29 14
|
1天前
|
缓存 负载均衡 网络协议
【亮剑】一次完整的 HTTP 请求过程,包括 DNS 解析、TCP 握手、HTTP 请求和响应等环节
【4月更文挑战第30天】本文介绍了HTTP请求的重要性和详细过程。首先,DNS解析将域名转换为IP地址,通过递归和迭代查询找到目标服务器。接着,TCP三次握手建立连接。然后,客户端发送HTTP请求,服务器处理请求并返回响应。最后,理解这个过程有助于优化网站性能,如使用DNS缓存、HTTP/2、Keep-Alive、CDN和负载均衡等实践建议。
|
3天前
|
JSON 编解码 Go
Golang深入浅出之-HTTP客户端编程:使用net/http包发起请求
【4月更文挑战第25天】Go语言`net/http`包提供HTTP客户端和服务器功能,简化高性能网络应用开发。本文探讨如何发起HTTP请求,常见问题及解决策略。示例展示GET和POST请求的实现。注意响应体关闭、错误处理、内容类型设置、超时管理和并发控制。最佳实践包括重用`http.Client`,使用`context.Context`,处理JSON以及记录错误日志。通过实践这些技巧,提升HTTP编程技能。
16 1
|
3天前
|
前端开发 API UED
AngularJS的$http服务:深入解析与进行HTTP请求的技术实践
【4月更文挑战第28天】AngularJS的$http服务是核心组件,用于发起HTTP请求与服务器通信。$http服务简化了通信过程,通过深入理解和实践,能构建高效、可靠的前端应用。
|
4天前
|
Go 开发者
Golang深入浅出之-HTTP客户端编程:使用net/http包发起请求
【4月更文挑战第24天】Go语言的`net/http`包在HTTP客户端编程中扮演重要角色,但使用时需注意几个常见问题:1) 检查HTTP状态码以确保请求成功;2) 记得关闭响应体以防止资源泄漏;3) 设置超时限制,避免长时间等待;4) 根据需求处理重定向。理解这些细节能提升HTTP客户端编程的效率和质量。
15 1
|
5天前
|
存储 缓存 开发框架
Flutter的网络请求:使用Dart进行HTTP请求的技术详解
【4月更文挑战第26天】了解Flutter网络请求,本文详述使用Dart进行HTTP请求
|
6天前
|
JSON 数据格式 索引
ES 查看索引的属性的http请求
在 Elasticsearch 中,要查看索引的属性,可以通过发送 HTTP 请求来执行以下操作: 1. **获取索引的映射(Mapping)**: 可以使用 `GET` 请求访问 Elasticsearch 的 `_mapping` 端点来获取特定索引的映射信息。 示例请求: ```http GET http://<elasticsearch_host>:<port>/<index_name>/_mapping ``` 2. **获取索引的设置(Settings)**: 可以使用 `GET` 请求访问 Elasticsearch 的 `_setting
|
6天前
|
网络架构 Python
在Flask中,如何定义路由并处理HTTP请求的不同方法(GET、POST等)?
【4月更文挑战第25天】在Flask中,使用`@app.route()`装饰器定义路由,如`/hello`,处理GET请求返回&#39;Hello, World!&#39;。通过添加`methods`参数,可处理不同HTTP方法,如POST请求。单一函数可处理多种方法,通过检查`request.method`区分。动态路由使用 `&lt;variable_name&gt;` 传递URL变量到视图函数。这些基础构成处理HTTP请求的Flask应用。
14 1
|
6天前
|
JSON API 数据格式
使用RestTemplate发送HTTP请求
使用RestTemplate发送HTTP请求
10 0
|
7天前
|
JSON 测试技术 API
Python的Api自动化测试使用HTTP客户端库发送请求
【4月更文挑战第18天】在Python中进行HTTP请求和API自动化测试有多个库可选:1) `requests`是最流行的选择,支持多种请求方法和内置JSON解析;2) `http.client`是标准库的一部分,适合需要低级别控制的用户;3) `urllib`提供URL操作,适用于复杂请求;4) `httpx`拥有类似`requests`的API,提供现代特性和异步支持。根据具体需求选择,如多数情况`requests`已足够。
13 3