web服务器需要对外发送请求(URLConnection)

12 篇文章 0 订阅

某些原因,我们web服务器需要对另一台服务器发送请求,就需要用到URLConnection这个类,首先看看官方文档:

  • 抽象类URLConnection是表示应用程序和URL之间的通信链接的所有类的超类。 该类的实例可以用于从URL引用的资源中读取和写入。 通常,创建与URL的连接是一个多步骤过程:  
    1. 通过在URL上调用openConnection方法创建连接对象。
    2. 设置参数和一般请求属性被操纵。
    3. 使用connect方法实现与远程对象的实际连接。
    4. 远程对象变得可用。 可以访问头字段和远程对象的内容。  

简单来说,要发送请求 ,需要利用URL.openConnection用请求地址建立链接,并设置你的参数和头部属性等等,最后用connect进行实际链接,从而可以让我们web的服务器对另一台web服务器进行发送请求。(注意URLConnection是抽象类,必须利用URL.openConnection来获取)

 上面是URL类中的 openConnection方法,能看到返回的类型是URLConnecion.

接下来上代码,文档中有关于URLConnection的方法,就不具体介绍

注意:

遇到中文的时候记得编码,输入输出流的编码方式.(重点)

out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
  public static String sendGet(String url, JSONObject requestProperty) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            if (requestProperty.size()!=0&&requestProperty!=null){
                for (Map.Entry<String, Object> entry:requestProperty.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), (String) entry.getValue());
                }
            }
            // 建立实际的连接
            connection.connect();
//            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
//            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

上面是自己封装的get请求方法,能看到我是从json格式的中读取了一些属性来设置当前该次请求的通用请求属性,也可以说是头部,最后用输入流去读取返回的参数。

public static String sendPost(String url, JSONObject requestProperty, JSONObject param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性(首部键值对)
            if (requestProperty.size() != 0 && requestProperty != null) {
                for (Map.Entry<String, Object> entry : requestProperty.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), (String) entry.getValue());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
           in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += 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();
            }
        }
        return result;
    }

上面是自己封装的post请求方法,能看到我是从json格式的中读取了一些属性来设置当前该次请求的通用请求属性,用输出流把请求参数传过去,最后用输入流去读取返回的参数。(设置该次请求的头部和请求参数不同,头部可以利用setRequestProperty设置)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值