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();  
        }  
    }  
 
}  


相关文章
|
14天前
|
API 数据安全/隐私保护
Haskell中的HTTP请求:代理与响应状态检查
Haskell中的HTTP请求:代理与响应状态检查
|
2月前
|
JSON Java 数据格式
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
112 25
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
|
1月前
|
缓存 应用服务中间件 Apache
HTTP 范围Range请求
HTTP范围请求是一种强大的技术,允许客户端请求资源的部分内容,提高了传输效率和用户体验。通过正确配置服务器和实现范围请求,可以在视频流、断点续传下载等场景中发挥重要作用。希望本文提供的详细介绍和示例代码能帮助您更好地理解和应用这一技术。
107 19
|
2月前
|
JSON JavaScript 前端开发
什么是HTTP POST请求?初学者指南与示范
HTTP POST请求是一种常用的HTTP方法,主要用于向服务器发送数据。通过合理设置请求头和请求主体,可以实现数据的可靠传输。无论是在客户端使用JavaScript,还是在服务器端使用Node.js,理解和掌握POST请求的工作原理和应用场景,对于Web开发至关重要。
411 18
|
2月前
|
JSON 数据格式
.net HTTP请求类封装
`HttpRequestHelper` 是一个用于简化 HTTP 请求的辅助类,支持发送 GET 和 POST 请求。它使用 `HttpClient` 发起请求,并通过 `Newtonsoft.Json` 处理 JSON 数据。示例展示了如何使用该类发送请求并处理响应。注意事项包括:简单的错误处理、需安装 `Newtonsoft.Json` 依赖,以及建议重用 `HttpClient` 实例以优化性能。
92 2
|
2月前
|
Web App开发 大数据 应用服务中间件
什么是 HTTP Range请求(范围请求)
HTTP Range 请求是一种非常有用的 HTTP 功能,允许客户端请求资源的特定部分,从而提高传输效率和用户体验。通过合理使用 Range 请求,可以实现断点续传、视频流播放和按需加载等功能。了解并掌握 HTTP Range 请求的工作原理和应用场景,对开发高效的网络应用至关重要。
252 16
|
2月前
|
安全 Java API
java如何请求接口然后终止某个线程
通过本文的介绍,您应该能够理解如何在Java中请求接口并根据返回结果终止某个线程。合理使用标志位或 `interrupt`方法可以确保线程的安全终止,而处理好网络请求中的各种异常情况,可以提高程序的稳定性和可靠性。
64 6
|
2月前
|
Web App开发 网络安全 数据安全/隐私保护
Lua中实现HTTP请求的User-Agent自定义
Lua中实现HTTP请求的User-Agent自定义
|
Java Apache Spring
Java发送Http请求(HttpClient)
Java发送Http请求(HttpClient)
10613 2
|
Java 网络安全 数据格式

热门文章

最新文章