java实现HTTP请求(一)

HttpURLConnection实现HTTP请求,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。(不推荐)

package com.rhine.blog.http;

import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
    /**
     * get 请求
     * @param httpurl 拼接完的URL地址
     * @return
     */
    public static String sendByGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            URL url = new URL(httpurl);// 创建远程url连接对象
            connection = (HttpURLConnection) url.openConnection();// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection.setRequestMethod("GET");  // 设置连接方式:get
            connection.setConnectTimeout(15000); //设置连接主机服务器的超时时间:15000毫秒
            connection.setReadTimeout(60000);    //设置读取远程返回的数据时间:60000毫秒
            connection.connect();// 发送请求
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 封装输入流is,并指定字符集
                StringBuffer sbf = new StringBuffer(); // 存放数据
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } 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;
    }

    /**
     * post 请求
     * @param httpUrl
     * @param param
     * @param contentType 常见的几种:application/x-www-form-urlencoded
     *                    multipart/form-data  application/json  text/xml
     * @return
     */
    public static String sendByPost(String httpUrl,String param,String contentType) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();//通过远程url连接对象打开连接
            connection.setRequestMethod("POST");//设置连接请求方式
            connection.setConnectTimeout(15000);//设置连接主机服务器超时时间:15000毫秒
            connection.setReadTimeout(60000);   //设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setDoOutput(true);       // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoInput(true);        // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            if(StringUtils.isEmpty(contentType)){
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }else {
                connection.setRequestProperty("Content-Type", contentType);
            }

            // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            os = connection.getOutputStream();  // 通过连接对象获取一个输出流
            os.write(param.getBytes());         // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                //对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }
}

Content-type的几种常见类型:

1、application/x-www-form-urlencoded

1)浏览器的原生form表单
2) 提交的数据按照 key1=val1&key2=val2 的方式进行编码,key和val都进行了URL转码

POST [http://www.example.com](http://www.example.com) HTTP/1.1 
Content-Type: application/x-[www-form-urlencoded](http://www-form-urlencoded);charset=utf-8 

title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3 

2、multipart/form-data

常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctype 等于这个值。

<form action="/" method="post" enctype="multipart/form-data">
  <input type="text" name="description" value="some text">
  <input type="file" name="myFile">
  <button type="submit">Submit</button>
</form>

3、application/json

消息主体是序列化后的 JSON 字符串,这个类型越来越多地被大家所使用

POST [http://www.example.com](http://www.example.com) HTTP/1.1 
Content-Type: application/json;charset=utf-8 

{"title":"test","sub":[1,2,3]}

这种方案,可以方便的提交复杂的结构化数据,特别适合 RESTful 的接口。各大抓包工具如 Chrome 自带的开发者工具、Firebug、Fiddler,都会以树形结构展示 JSON 数据,非常友好。

4、text/xml

是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范

POST [http://www.example.com](http://www.example.com) HTTP/1.1 
Content-Type: text/xml 
<!--?xml version="1.0"?--> 
<methodcall> 
    <methodname>examples.getStateName</methodname> 
    <params> 
        <param> 
            <value><i4>41</i4></value> 
    </params> 
</methodcall> 
posted @ 2020-03-20 09:12  An-Optimistic-Person  阅读(464)  评论(0)    收藏  举报