使用Java发送http请求,不使用第三方库

HTTP协议是现在互联网广泛使用的数据传输协议,几乎任何一种编程语言都实现了这个协议。Java语言是做web应用(服务器端应用)的强大语言。不过,现在我们使用Java语言来做客户端,发送http请求到服务器,并获取服务器的响应结果。

目前,绝大多数人都会使用第三方的框架,比如Apache的httpclient,在高版本的java中甚至内置了一个轻量级的http客户端类,但我这次使用原生的方式去发送,不依赖任何第三方的东西,使用JavaSE就可以完成。

  • Java发送http请求需要使用一个叫URL的类,他的构造方法可以接受一个网址,就是我们想要发送请求的地址。
  • 然后,通过这个URL的实例,就可以打开一个连接。
  • 之后,通过这个连接可以读写数据。
  • 最后,关闭数据读写连接。

下面,展示代码,并附上说明:

    public String httpRequest(String url) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        
        // 设置http请求头,content-type为你发送请求参数的数据格式,目前来说application/json用的比较多,常用的三种
        // 1.application/json 2.application/x-www-form-urlencoded 3.multipart/form-data; boundary=xxxxxxx
        // 第一种,就是使用json的格式发送请求参数,类似{"name":"xxx","age":18},第二种使用urlencode的形式发送请求参数
        // 类似name=xxx&age=18,第三种就比较复杂点了,可以支持上传文件,本次不做示例展示
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//        connection.setRequestProperty("content-type", "application/json;charset=utf-8"); // json格式发送数据
//        connection.setRequestProperty("content-type", "multipart/form-data; boundary=xxxxxxx"); // 表单数据发送
        
        // 必须设置setDoOutput为true才能向请求中写数据,post请求必须设置true,如果是GET请求,下面前两行可以省略
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); 
        connection.connect();
        
        // 获取数据写入流,如果是GET请求,这里不需要,因为GET请求不需要写数据
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write("name=xxx&age=18");
//        bufferedWriter.write("{\"name\":\"xxx\",\"age\":18}"); // json格式发送
        // 写完数据一定要flush
        bufferedWriter.flush();
        bufferedWriter.close();
StringBuilder content
= new StringBuilder(); if (connection.getResponseCode() == 200) { // 获取数据读取流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str; while ((str = bufferedReader.readLine()) != null) { content.append(str); } bufferedReader.close(); return content.toString(); } else { System.err.println(connection.getResponseCode()); } return ""; }

以上代码,只要稍作调整,就可以完成GET POST PUT DELETE等http请求,非常简单。

 

最后,贴出常用的请求最精简代码:

    /**
     * 发送get请求
     * @param url
     * @return
     * @throws Exception
     */
    public String get(String url) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }
    
    /**
     * 发送post请求,请求参数为urlencode格式
     * @param url
     * @param params 类似 name=xxx&age=18
     * @return
     * @throws Exception
     */
    public String post(String url, String params) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.connect();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write(params);
        bufferedWriter.flush();
        bufferedWriter.close();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }
    
    /**
     * 发送post请求,请求参数为json格式
     * @param url
     * @param params 类似 {"name":"xxx","age":18}
     * @return
     * @throws Exception
     */
    public String postJson(String url, String params) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestProperty("content-type", "application/json;charset=utf-8");
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.connect();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bufferedWriter.write(params);
        bufferedWriter.flush();
        bufferedWriter.close();
        StringBuilder content = new StringBuilder();
        if (connection.getResponseCode() == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                content.append(str);
            }
            bufferedReader.close();
            return content.toString();
        } else {
            System.err.println(connection.getResponseCode());
        }
        return "";
    }

 

posted @ 2020-05-29 11:00  迷茫小左  阅读(1364)  评论(0编辑  收藏  举报