使用java代码模拟HTTP GET与POST请求

import java.io.*;
import java.net.*;

/**
 * http GET与POST请求处理
 * java代码示例
 *
 * Created by IntelliJ IDEA.
 * User: volcano
 * Date: 2019/11/8
 * Time: 19:36
 */
public class Connection {

    /**
     * 处理http get请求
     * @param path
     * @return
     * @throws MalformedURLException
     */
    public static String doGet(String path) {

        URL url = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedReader br = null;
        String response = "";
        try {
            //通过请求路径实例化一个URL对象
            url = new URL(path);
            //通过实例化的URL对象创建一个http连接并转换为HttpURLConnection类型
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式,这里我设置为GET方式
            conn.setRequestMethod("GET");
            //因为GET方式是获取数据用的,所以需要读取http的响应内容,因此connection需要启用输入流(doInput的默认值为true,所以实际上也可以不写这行代码)
//        conn.setDoInput(true);
            //因为GET方式没有请求体,所以不需要启用输出流(doOutput的默认值为false,所以实际上也可以不写这行代码)
//        conn.setDoInput(false);
            //是否启用缓存,默认是启用的,我这里设置为不启用
            conn.setUseCaches(false);

            //通过conn,获取InputStream对象
            inputStream = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));

            String line = "";
            StringBuffer buffer = new StringBuffer();

            //按行读取服务端响应的内容
            while ((line = br.readLine()) != null){
                buffer.append(line + System.lineSeparator());
            }

            response = buffer.toString();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭io对象以及connection对象
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                conn.disconnect();
            }

            //打印到控制台,查看响应内容
            System.out.println(response);
            return response;
        }
    }

    /**
     * 处理http POST请求
     * @param path
     * @return
     */
    public static String doPost(String path, String body) {

        URL url = null;
        HttpURLConnection conn = null;
        OutputStream outputStream = null;
        BufferedWriter bw = null;
        InputStream inputStream = null;
        BufferedReader br = null;
        String response = "";
        try {
            url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);

            //先向服务端发送请求体内容
            outputStream = conn.getOutputStream();
            bw = new BufferedWriter(new OutputStreamWriter(outputStream));
            bw.write(body);
            bw.flush();

            //然后再读取服务端响应内容
            inputStream = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            StringBuffer buffer = new StringBuffer();
            while ((line = br.readLine()) != null){
                buffer.append(line);
            }
            response = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭io对象以及connection对象
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                conn.disconnect();
            }

            System.out.println(response);
            return response;
        }
    }

    /**
     * 测试get与post方法
     * @param args
     */
    public static void main(String[] args) {

        String path_get = "http://www.openldap.org/doc/admin24/intro.html#What%20is%20LDAP";
        doGet(path_get);

        //这里的地址可以依据自己的情况而定哦
        String path_post = "http://localhost:port/login";
        String body = "{\"login\":{\"userName\":\"test\",\"passwd\":\"qq123456\"}}";
        doPost(path_post,body);

    }

}

你可能感兴趣的:(使用java代码模拟HTTP GET与POST请求)