您现在的位置是:网站首页>文章详情文章详情

java版的requests请求类,实现GET、POST

inlike2020-09-01 原创文章 浏览(1481) 评论(0) 喜欢(21)

简介Java版本的requests请求库,像Python一样实现请求。

只实现了主要的POST和GET请求功能。使用Java内置的java.net.URL、java.net.HttpURLConnection包处理请求,没有实现JSON的处理,Java没有内置JSON处理包,需要通过第三方包来实现。

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.lang.Exception;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;

//import org.json.JSONObject;


public class requests {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     *            //     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String get(String url, Map<String, String> headers) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
//        Map<String, String> response = new HashMap<String, String>();
        JSONObject response = new JSONObject();
        int status;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            Set<String> keys = headers.keySet(); //此行可省略,直接将map.keySet()写在for-each循环的条件中
            for (String key : keys) {
                System.out.println("key值:" + key + " value值:" + headers.get(key));
                connection.setRequestProperty(key, headers.get(key));
            }
            // 超时时间
            connection.setConnectTimeout(2 * 1000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            status = connection.getResponseCode();
            response.put("status", Integer.toString(status));
            Map<String, List<String>> response_headers = connection.getHeaderFields();
            keys = response_headers.keySet(); //此行可省略,直接将map.keySet()写在for-each循环的条件中
            JSONObject headers_json = new JSONObject();
            for (String key : keys) {
                if (key != null) {
                    headers_json.put(key, response_headers.get(key));
                }
            }
            response.put("headers", headers_json);
            URL response_url = connection.getURL();
            response.put("url", response_url.toString());
            for (String key : response_headers.keySet()) {
                System.out.println(key + ": " + response_headers.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
                status = 503;
            }
        }
        response.put("content", result.toString());
        return JSONObject.valueToString(response);
//        return response.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String post(String url, String param, Map<String, String> headers) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
//        Map<String, String> response = new HashMap<String, String>();
        JSONObject response = new JSONObject();
        int status;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            Set<String> keys = headers.keySet(); //此行可省略,直接将map.keySet()写在for-each循环的条件中
            for (String key : keys) {
                System.out.println("key值:" + key + " value值:" + headers.get(key));
                conn.setRequestProperty(key, headers.get(key));
            }
            // 超时时间
            conn.setConnectTimeout(2 * 1000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            Map<String, List<String>> response_headers = conn.getHeaderFields();
            // 遍历所有的响应头字段
//            String setCookie = connection.getHeaderField("Set-Cookie");
            keys = response_headers.keySet(); //此行可省略,直接将map.keySet()写在for-each循环的条件中
            JSONObject headers_json = new JSONObject();
            for (String key : keys) {
                if (key != null) {
                    headers_json.put(key, response_headers.get(key));
                }
            }
            response.put("headers", headers_json);
            status = conn.getResponseCode();
            response.put("status", Integer.toString(status));
            URL response_url = conn.getURL();
            response.put("url", response_url.toString());
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                status = 503;
            }
        }
        response.put("content", result.toString());

        return response.toString();
    }


    public static void main(String[] args) {
        /*
         测试函数
         */
        Map<String, String> h = new HashMap<String, String>();
        h.put("Content-Type", "application/json");
        post("http://localhost:6006/data", result, h);
        System.out.println(result);
    }
}


很赞哦! ( 21)
    《Python实战进阶》
    None
    None
    夏至已深

站点信息

  • 建站时间:2019-5-24
  • 网站程序:like in love
  • 主题模板《今夕何夕》
  • 文章统计:104条
  • 文章评论:***条
  • 微信公众号:扫描二维码,关注我们
  • 个人微信公众号