zoukankan      html  css  js  c++  java
  • HTTP请求的三种方式

    HTTP请求的三种方式

    1、通过HttpURLConnection发送http请求,得到返回的数据,(HttpURLConnection是URLConnection的子类,URLConnection代码写法和HttpURLConnection代码一致,建议使用HttpURLConnection,HttpURLConnection请求使用JDK原生提供的net,无需其他jar包)

    案例:

    package demo;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Test3 {
    
        public static String sendRequest(String urlParam,String requestType) {
    
            HttpURLConnection con = null;  
    
            BufferedReader buffer = null; 
            StringBuffer resultBuffer = null;  
    
            try {
                URL url = new URL(urlParam); 
                //得到连接对象
                con = (HttpURLConnection) url.openConnection(); 
                //设置请求类型
                con.setRequestMethod(requestType);  
                //设置请求需要返回的数据类型和字符集类型
                con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
                //允许写出
                con.setDoOutput(true);
                //允许读入
                con.setDoInput(true);
                //不使用缓存
                con.setUseCaches(false);
                //得到响应码
                int responseCode = con.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //得到响应流
                    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://www.baidu.com";
            System.out.println(sendRequest(url,"POST"));
        }
        
    }

    2、通过HttpClient发送http请求,得到返回数据(需要在pom.xml中添加依赖<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version></dependency>,此方法使用比较方便,比较广泛应用)

     案例:

    package com.wiseweb;
    
    import java.io.IOException;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class Test1 {
        public static String sendPost(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(urlParam);
            // 设置post请求超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            postMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(postMethod);
    
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            return result;
        }
        public static String sendGet(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建GET请求方法实例对象
            GetMethod getMethod = new GetMethod(urlParam);
            // 设置post请求超时时间
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            getMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(getMethod);
    
            String result = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
            return result;
        }
        public static void main(String[] args) throws HttpException, IOException {
            String url ="http://www.baidu.com";
            System.out.println(sendPost(url));
            System.out.println(sendGet(url));
        }
    }
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

    3、通过Socket发送http请求或者https请求,得到返回数据(http 的连接很简单,是无状态的;HTTPS 协议是由 SSL+HTTP 协议构建的可进行加密传输、身份认证的网络协议,比 http 协议安全。Socket请求使用JDK原生提供的net,无需其他jar包)

    案例:

    package demo;
    
    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
    ");    
            bufferedWriter.write("Host: " + this.host + "
    ");    
            bufferedWriter.write("
    ");    
            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
    ");    
                bufferedWriter.write("Host: " + this.host + "
    ");    
                bufferedWriter.write("Content-Length: " + data.length() + "
    ");    
                bufferedWriter.write("Content-Type: application/x-www-form-urlencoded
    ");    
                bufferedWriter.write("
    ");    
                bufferedWriter.write(data);    
    
                bufferedWriter.write("
    ");    
                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();  
            }  
        }  
    }
  • 相关阅读:
    Atitit 软件知识点分类体系 分类 按照书籍的分类 学科分类 体系与基础部分 计算机体系结构 硬件接口技术(usb,agp,pci,div,hdmi) os操作系统 中间件 语言部分
    Atitit spring注解事务的demo与代码说明 目录 1.1. Spring框架中,要如何实现事务?有一个注解,@EnableTransactionManagement 1 1.2. 事务管理
    Atitit springboot mybatis spring 集成 Springboot1.4 mybatis3.4.6 /springbootMybatis 目录 1.1. 设置map
    Atitit 计算机系统结构 计算机系统结构 Cpu 存储 cache 指令系统 目录 Line 56: 第2章指令系统设计 指令格式 寻址方式 1 Line 64: 第3章CPU及其实现
    Atitit 微服务 分布式 区别 微服务的判断标准 目录 1.1. 区别 微服务侧重于微小服务进程隔离级别,分布式侧重于机器隔离 1 2. 微服务是一种架构, 。多微才叫微? 1 2.1. 微服务
    Atitit spirngboot 访问 html文件总结 自设计web服务器原理与实现 Url路由压力,读取url,获得项目更路径绝对路径,拼接为文件路径。读取文建内容输出即可 目录路径 u
    Atitit 现代信息检索 Atitit 重要章节 息检索建模 检索评价 第8章 文本分类 Line 210: 第9章 索引和搜索 第11章 Web检索 第13章 结构化文本检索 目录 L
    Atitit 定时器timer 总结 目录 1.1. Js定时器 window.setInterval 1 2. Java定时器 timer 1 1.1.Js定时器 window.setInter
    Atitit spring5 集成 mybatis 注解班
    Atitit 微服务的一些理论 目录 1. 微服务的4个设计原则和19个解决方案 1 2. 微服务应用4个设计原则 1 2.1. AKF拆分原则 2 2.2. 前后端分离 2 2.3. 无状态服务
  • 原文地址:https://www.cnblogs.com/lw-20171224/p/13753121.html
Copyright © 2011-2022 走看看