Java发送http的get、post、put请求

时间:2025-03-25 18:24:54
1. HTTP GET请求
/**
     * 向指定URL发送GET方法的请求
     * @param url   发送请求的URL        
     * @param param   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL   所代表远程资源的响应结果
*/

    public static String httpGet(String reqUrl, Map<String, String> headers){
        return httpRequest(reqUrl, headers);
    }


    public static String httpRequest(String reqUrl,  Map<String, String> otherHeaders){
        URL url;
        try {
            url = new URL(reqUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) ();

            //设置用户名密码
            String userName = "admin";
            String password = "nsfocus";
            String auth = userName + ":" + password;
            BASE64Encoder enc = new BASE64Encoder();
            String encoding = (());    
            (true);
//          (true);
//          (false);
//          //默认为GET请求
//          ("GET");
            ("Authorization", "Basic " + encoding);

            // 设置通用的请求属性
            for(Entry<String, String> entry : ()){
             ((), ());               
            }
            // 建立实际的连接
            ();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader((),"utf-8"));
            StringBuilder sb = new StringBuilder();
            String line="";
            while ((line = ()) != null){
                (line);
            }
            ();
            ();
            return ();

            //对返回数据进行解析处理
            String result = ();
            root = (result);
            Iterator<JsonNode> rootNode = ();
            while(()){
                JsonNode c = ();
                JsonNode sites = ("site");
                String ids = ("id").toString();
                //substring方法,"qiqishuang"去除引号
                id = (1, ()-1);
            }
        } catch (IOException e) {
            ("error while getting  request: {}", ());
            return id;
        } 
    }
2. HTTP POST请求
/**
     * 向指定URL发送POST方法的请求
     * @param url   发送请求的URL
     * @return URL   所代表远程资源的响应结果
*/

    public static String httpPost(String reqUrl, String content, Map<String, String> headers){
        return httpRequest(reqUrl, "POST", content, headers);
    }


    public static String httpRequest(String reqUrl, String method, String content, 
    Map<String, String> headers){
        URL url;
        try {
            // 打开和URL之间的连接
            url = new URL(reqUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            (true);
            // Read from the connection. Default is true.
            (true);
            // Set the post method. Default is GET
            (method);
            // Post cannot use caches
            (false);
            (true);
            for(Entry<String, String> entry : ()){
                ((), ());                
            }
            ();
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());
            // The URL-encoded contend
            (content); 
            ();
            (); // flush and close
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader((),"utf-8"));
            StringBuilder sb = new StringBuilder();
            String line="";
            while ((line = ()) != null){
                (line);
            }
            ();
            ();
            return ();
        } catch (IOException e) {
            ("error while posting request: {}", ());
            return null;
        } 
    }
3. HTTP PUT请求
    public void httpPut(String dst_ip) {
        GlobalConfig global = GlobalConfig.getInstance();
        String urlStr = global.sncHost + "/devices/1/acl/aclGroups/aclGroup";

        //create xml info pushed to controller
        String xmlInfo = createXmlInfo(dst_ip);

        //establish connection and push policy to snc controller
        try {
             URL url = new URL(urlStr);
             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
             conn.setRequestMethod("PUT");
             conn.setDoInput(true);
             conn.setDoOutput(true);
             OutputStream os = conn.getOutputStream();     
             os.write(xmlInfo.getBytes("utf-8")); 
             os.flush();
             os.close();         
             BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
             String line = "";
             String result = "";
             while( (line =br.readLine()) != null ){
                 result += line;
             }
             log.info(result);
             br.close();
        } catch (Exception e) {
            log.info("Error in pushing policy now");
            e.printStackTrace();  
        }
    }