• Http URLConnection 接口


     URL url = new URL();

    HttpURLConnection conn = new HttpURLConnection ();

    InputStream getInputStream()                 //获取URL连接的输入流,从而获得响应的内容

    OutputStream getOutputStream()           //获取URL的输出流 从而传递参数给服务器

    void setUseCaches();                              //设置URL连接的useCaches字段

    void setInstanceFellowRedirects()          // 设置是否应该执行HTTP重定向

    void setRequestProperty(String key,String value)   //设置一般请求属性

    int getRequesetCode()                                            //获得服务器响应码

    String getResponseMessage();                             //获取服务器响应信息

    String getRequestMessage()                                  //获取发送请求方法


    HttpURLConnection    请求获取URL引用的资源步骤如下

    1)创建HttpURLConnection 对象

    2)设置请求属性和对象参数

    3)如果是Get请求方式,由于HttpURLConnection默认使用Get方式,因此直接调用connect()方法连接即可建立连接;如果是以Post方式请求,则需要设置请求方式为Post

    以get方式向服务器发送请求,获取数据,代码如下

    //使用HttpURLConnection 打开连接

    HttpURLConnection  conUrl = (HttpURLConnection) url.openConnection();

    conUrl.connect();

    //得到读取的内容流

    InpuStremReader in = new InputStreamReader(conUrl.getInputStream());

    ...                   //通过InputStream读取数据

    in.close(); // 关闭inputStreamReader();

    conUrl.close(); //关闭HTTP请求

    以POST方式向服务器发送请求,提交参数给服务器,请求示例代码如下

    //使用HttpURLConnection打开连接

    HttpURLConnection con = (HttpURLConnection) url.openHttpURLConnection();

    //Http请求为Post,因此需要将setDoInput,setOutput设置为true

    con.setDoInput(true);

    con.setDoOutput(true);

    con.setRequsetMethod("POST");  //设置请求方式为post

    con.setUseCaches(false);  //Post请求不能使用缓存

    //请求对象的属性,参数配置必要要在connect之前完成

    //获取输出流此处getOutputStream()调用隐式的建立连接

    //因此,本例无需调用connect()方法进行连接、

    OutputStream out = con.getOutputStream();

    ...                                 //执行输出操作

    out.flush();                  //刷新

    out.close();                //刷新

    con.disconnection(); //关闭Http连接



  • 相关阅读:
    pycharm的常规使用
    python-引用/模块
    6-4 函数
    5-21文件的操作
    5-21python数据类型
    python-基础
    5-7接口测试工具之jmeter的使用
    接口测试基础
    把命令结果作为变量赋值
    shell变量子串
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11781898.html
Copyright © 2020-2023  润新知