HttpURLConnection的用法

1、Maven依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>

2、请求响应流程

在这里插入图片描述

3、Get请求方式举例

代码:

public class Test {
    public static void main(String[] args) {
        System.out.println(doGet("http://www.baidu.com"));
    }

    /**
     * 测试get请求方式
     *
     * @param apiUrl 链接
     * @return 请求返回值
     * @author 明快de玄米61
     * @date 2021/09/05
     */
    private static String doGet(String apiUrl) {
        HttpURLConnection connection = null;
        InputStream in = null;
        BufferedReader reader = null;
        try {
            // 构造一个URL对象
            URL url = new URL(apiUrl);
            // 获取URLConnection对象
            connection = (HttpURLConnection) url.openConnection();
            // getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用connect()也可以)
            in = connection.getInputStream();
            // 通过InputStreamReader将字节流转换成字符串,在通过BufferedReader将字符流转换成自带缓冲流
            reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line = null;
            // 按行读取
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭连接和流
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

4、POST请求方式举例

例1:获取token
代码
public class Test {
    public static void main(String[] args) {
        System.out.println("token:" + doPost("接口地址", "root", "123456", "default"));
    }

    /**
     * 测试post请求方式
     * @author 明快de玄米61
     * @date   2021/9/6 23:12
     * @param  apiUrl 接口地址
     * @param username 用户名
     * @param password 密码
     * @param tenantUrl 租户标识
     * @return
     **/
    private static String doPost(String apiUrl, String username, String password, String tenantUrl) {
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStream in = null;
        String idToken = null;
        try {
            // 构造一个URL对象
            URL url = new URL(apiUrl);
            // 获取URLConnection对象
            conn = (HttpURLConnection) url.openConnection();
            // 限制socket等待建立连接的时间,超时将会抛出java.net.SocketTimeoutException
            conn.setConnectTimeout(3000);
            // 限制输入流等待数据到达的时间,超时将会抛出java.net.SocketTimeoutException
            conn.setReadTimeout(3000);
            // 设定请求的方法为"POST",默认是GET
            conn.setRequestMethod("POST");
            // 设置传送的内容类型是json格式
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 接收的内容类型也是json格式
            conn.setRequestProperty("Accept", "application/json;charset=utf-8");
            // 设置是否从httpUrlConnection读入,默认情况下是true
            conn.setDoInput(true);
            // 由于URLConnection在默认的情况下不允许输出,所以在请求输出流之前必须调用setDoOutput(true)。为一个HTTP URL将doOutput设置为true时,请求方法将由GET变为POST
            conn.setDoOutput(true);
            // 是否使用缓存,Post方式不能使用缓存
            conn.setUseCaches(false);
            // 准备数据
            JSONObject json = new JSONObject();
            json.put("username", username);
            json.put("password", DigestUtils.md5Hex(password));
            json.put("tenantUrl", tenantUrl);
            // 返回一个OutputStream,可以用来写入数据传送给服务器
            out = conn.getOutputStream();
            // 将数据写入到输出流中
            out.write(json.toString().getBytes(StandardCharsets.UTF_8));
            // 刷新管道
            out.flush();
            // 建立连接
            conn.connect();
            // 判断数字响应码是否是200
            int responseCode = conn.getResponseCode();
            String result = "";
            if (responseCode == 200) {
                // 获取输入流
                in = conn.getInputStream();
                // 获取返回的内容
                StringWriter sw = new StringWriter();
                InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
                char[] buffer = new char[4096];
                for (int n = 0; -1 != (n = reader.read(buffer)); ) {
                    sw.write(buffer, 0, n);
                }
                result = sw.toString();
                // 处理返回的内容
                if (result != null && !"".equals(result.trim())) {
                    JSONObject rjo = JSONObject.parseObject(result, Feature.OrderedField);
                    if (rjo != null && rjo.containsKey("retCode")) {
                        int retCode = rjo.getInteger("retCode");
                        if (retCode == 0 && rjo.containsKey("data")) {
                            JSONObject data = rjo.getJSONObject("data");
                            if (null != data && data.containsKey("idToken")) {
                                // 获取最终想要的数据
                                idToken = data.getString("idToken");
                            }
                        }
                    }
                }
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException("获取token出现连接/超时异常");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取token时执行内部代码时出现异常");
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return idToken;
    }
}
结果
token:853b7c87-c16f-4e3b-96c4-9701fe3448ab
接口文档

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Postman访问示例

在这里插入图片描述
在这里插入图片描述

例2:获取知识图谱信息
代码
public class Test {
    public static void main(String[] args) {
        System.out.println("图谱结果:" + doPost("接口地址", "实体id", "token令牌", "图谱实例数量"));
    }

    private static String doPost(String apiUrl, String instanceId, String idToken, Integer number) {
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStream in = null;
        String result = null;
        try {
            URL url = new URL(apiUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Accept", "application/json;charset=utf-8");
            conn.setRequestProperty("Authorization", "Bearer " + idToken);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            JSONObject json = new JSONObject();
            json.put("pageNum", 0);
            json.put("pageSize", number);

            JSONObject data = new JSONObject();
            String[] status = { "on" };
            data.put("status", status);
            String[] instanceIdSet = { instanceId };
            data.put("instanceIdSet", instanceIdSet);
            String[] checked = { "on" };
            data.put("checked", checked);
            json.put("data", data);
            out = conn.getOutputStream();
            out.write(json.toString().getBytes("utf-8"));
            out.flush();
            conn.connect();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                in = conn.getInputStream();
                StringWriter sw = new StringWriter();
                InputStreamReader reader = new InputStreamReader(in, "utf-8");
                char[] buffer = new char[4096];
                for (int n = 0; -1 != (n = reader.read(buffer));) {
                    sw.write(buffer, 0, n);
                }
                result = sw.toString();
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException("调用获取图谱接口出现连接/超时异常");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用获取图谱接口执行内部代码时出现异常");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
接口文档

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Postman访问示例

在这里插入图片描述
在这里插入图片描述

例3:调用ES高级接口获取实体信息
代码
public class HTTPURLConnectionTest {
    public static void main(String[] args) {
        System.out.println("图谱结果:" + doPost("接口地址", "图谱id", "实体id", "token令牌"));
    }

    private static String doPost(String apiUrl, String ontologyId, String instanceId, String idToken) {
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStream in = null;
        String result = null;
        try {
            URL url = new URL(apiUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Accept", "application/json;charset=utf-8");
            conn.setRequestProperty("Authorization", "Bearer " + idToken);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            JSONObject json = new JSONObject();
            json.put("pageNum", 0);
            json.put("pageSize", 1);

            JSONObject data = new JSONObject();
            data.put("ontologyId", ontologyId);
            data.put("needProperties", true);
            JSONArray expresses = new JSONArray();
            JSONObject arr = new JSONObject();
            arr.put("sign", "=");
            arr.put("value", instanceId);
            arr.put("key", "id");
            arr.put("dataType", "String");
            expresses.add(arr);

            data.put("expresses", expresses);
            json.put("data", data);

            out = conn.getOutputStream();
            out.write(json.toString().getBytes("utf-8"));
            out.flush();
            conn.connect();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                in = conn.getInputStream();
                StringWriter sw = new StringWriter();
                InputStreamReader reader = new InputStreamReader(in, "utf-8");
                char[] buffer = new char[4096];
                for (int n = 0; -1 != (n = reader.read(buffer)); ) {
                    sw.write(buffer, 0, n);
                }
                result = sw.toString();
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException("调用ES高级查询接口出现连接/超时异常");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用ES高级查询接口执行内部代码时出现异常");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
接口文档

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Postman访问示例

在这里插入图片描述
在这里插入图片描述

5、参考

1、详解HttpURLConnection

2、URLConnection

6、拓展

1、CloseableHttpClient的用法

链接:CloseableHttpClient的用法

2、http协议切换为https协议(视情况使用,也不是所有https协议都要用这种方式)

如果http协议变成了https协议,我们需要更换HttpURLConnection的获取方式,如下:

// 构造一个URL对象
URL url = new URL("https://ip:port/XXX");
// 获取https连接
HttpsURLConnection urlConn = (HttpsURLConnection)url.openConnection();
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init((KeyManager[])null, new TrustManager[]{new NX509TrustManager()}, (SecureRandom)null);
SSLSocketFactory factory = sslContext.getSocketFactory();
urlConn.setSSLSocketFactory(factory);
HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String s, SSLSession sslsession) {
        return true;
    }
};
urlConn.setHostnameVerifier(hv);
// 将HttpsURLConnection连接对象转换成HttpURLConnection连接对象,其他的使用没有变化
HttpURLConnection conn = urlConn;
3、数据发送和数据接收方式说明

(1)、数据发送

  1. 使用String.format()方法直接拼接成字符串(应对:简单情况;优点:简单好用,方便快捷;缺点:应对复杂情况不好用)
  2. 使用阿里的fastjson依赖中的JsonObject,作用是创建JsonObject对象,用来存储传输参数,然后将JsonObject对象生成json字符串(应对:稍微复杂;优点:清晰明了;缺点:多次使用中字符串写错)
  3. 创建相应类来存储参数,然后使用阿里fastjson来将对象转换为json字符串(应对:复杂情况;优点:职责清晰明了,尤其是带有多个相同类型对象组成集合的情况,这种用JsonObject不够清晰明了;缺点:太重,简单情况不要使用)

(2)数据接收

  1. 使用阿里的fastjson依赖将返回字符串转换成JsonObject对象,然后拿出里面的数据(应对:简单情况;优点:简单方便,不用在写类了;缺点:应对复杂情况显得力不从心,代码不好维护)
  2. 创建接收数据的类,使用阿里的fastjson依赖将字符串转换成接收数据类,我方直接就可以使用(应对:复杂情况;优点:职责清晰明了;缺点:太重)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值