• java.net.URL


    说明

    • URLConnection
    • HttpURLConnection extends URLConnection

    Demo 请求API,不用发送参数

    // 目标地址
    URL url = new URL("https://api")
    // 转换
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection()
    // 设置请求方法
    urlConnection.setRequestMethod("GET")
    // 从此链接打开一个输入流,读取接口返回的数据,input到我们的内存中。
    urlConnection.inputStream.withReader("UTF-8", {
        Reader reader -> println(reader.text) }
    )

    Demo 请求API,发送参数

    URL baseUrl = new URL('https://api/')
    HttpURLConnection connection = (HttpURLConnection)baseUrl.openConnection()
    // 设置请求方法
    connection.setRequestMethod("POST")
    // 设置需要输出参数给对方
    connection.setDoOutput(true)
    // 设置请求输出参数类型
    connection.setRequestProperty("Content-Type","application/json")
    // 输出给对方参数
    connection.outputStream.withWriter { java.io.Writer writer -> writer << params}
    // 接受返回内容
    filebyte = connection.inputStream.getBytes()

    理解

    URL baseUrl = new URL("http://www.duchaoqun.cn")
    HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection()
    connection.setRequestMethod("GET")
    connection.setDoInput(true)
    def fileBytes = connection.inputStream.getBytes()
    GET/POST请求,不需要参数时,当我们需要通过这个URL连接从服务器获取数据到本地内存,就要设置DoInput为true(默认为true)。
    connection.setDoOutput(true)
    connection.outputStream.withWriter {...}
    POST请求,需要参数时,我们要从内存给远程一些参数,就需要设置DoOutput为true(默认为false),然后给它输出一些参数。
  • 相关阅读:
    golang ---cron
    Maven私库安装与配置
    Java8新特性之重复注解(repeating annotations)浅析
    String split
    如何将xml转为python中的字典
    json字符串和dict互转
    为什么空格拷贝到linux 会变成两个
    python之socket编程
    ntpdate设置
    Nginx配置ssl证书
  • 原文地址:https://www.cnblogs.com/duchaoqun/p/14009672.html
Copyright © 2020-2023  润新知