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

版权声明:本博客为博主原创博文,可以任意转载。转载请附上博客链接: http://blog.csdn.net/qiqishuang https://blog.csdn.net/qiqishuang/article/details/51644372

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) url.openConnection();

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

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

            //对返回数据进行解析处理
            String result = sb.toString();
            root = mapper.readTree(result);
            Iterator<JsonNode> rootNode = root.elements();
            while(rootNode.hasNext()){
                JsonNode c = rootNode.next();
                JsonNode sites = c.path("site");
                String ids = sites.path("id").toString();
                //substring方法,"qiqishuang"去除引号
                id = ids.substring(1, ids.length()-1);
            }
        } catch (IOException e) {
            log.error("error while getting  request: {}", e.getMessage());
            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();
            connection.setDoOutput(true);
            // Read from the connection. Default is true.
            connection.setDoInput(true);
            // Set the post method. Default is GET
            connection.setRequestMethod(method);
            // Post cannot use caches
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            for(Entry<String, String> entry : headers.entrySet()){
                connection.setRequestProperty(entry.getKey(), entry.getValue());                
            }
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());
            // The URL-encoded contend
            out.writeBytes(content); 
            out.flush();
            out.close(); // flush and close
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(),"utf-8"));
            StringBuilder sb = new StringBuilder();
            String line="";
            while ((line = reader.readLine()) != null){
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            return sb.toString();
        } catch (IOException e) {
            log.error("error while posting request: {}", e.getMessage());
            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();  
        }
    }

猜你喜欢

转载自blog.csdn.net/qiqishuang/article/details/51644372