博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java成神之——HttpURLConnection访问api
阅读量:5097 次
发布时间:2019-06-13

本文共 2270 字,大约阅读时间需要 7 分钟。

HttpURLConnection

访问get资源

HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();int responseCode = connection.getResponseCode();InputStream inputStream;if (200 <= responseCode && responseCode <= 299) {    inputStream = connection.getInputStream();} else {    inputStream = connection.getErrorStream();}BufferedReader in = new BufferedReader( new InputStreamReader(inputStream));StringBuilder response = new StringBuilder();String currentLine;while ((currentLine = in.readLine()) != null) response.append(currentLine);in.close();response.toString();

访问post资源

HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();connection.setRequestProperty("Content-Type", "application/json");connection.setDoOutput(true);OutputStream out = connection.getOutputStream();out.write("post传递的数据".getBytes());out.close();InputStream in = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));String line = null;while ((line = reader.readLine()) != null) {    System.out.println(line);}in.close();if (connection != null) connection.disconnect();if (out != null) out.close();if (in != null) in.close();

访问Delete资源

HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();connection.setRequestProperty("Content-Type", "application/json");connection.setRequestMethod("DELETE");connection.setDoInput(true);Map
> map = connection.getHeaderFields();StringBuilder sb = new StringBuilder();Iterator
>> iterator = map.entrySet().iterator();while(iterator.hasNext()) { Map.Entry
> entry = iterator.next(); sb.append(entry.getKey()); sb.append('=').append('"'); sb.append(entry.getValue()); sb.append('"'); if(iterator.hasNext()){ sb.append(',').append(' '); }}System.out.println(sb.toString());if (connection != null) connection.disconnect();

获取状态码

HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();connection.setRequestMethod("HEAD");int code = connection.getResponseCode();connection.disconnect();

结语

本文章是java成神的系列文章之一如果你想知道,但是本文没有的,请下方留言我会第一时间总结出来并发布填充到本文

转载于:https://www.cnblogs.com/ye-hcj/p/9750367.html

你可能感兴趣的文章
[Typescript] Specify Exact Values with TypeScript’s Literal Types
查看>>
Illustrated C#学习笔记(一)
查看>>
理解oracle中连接和会话
查看>>
Scrapy实战篇(三)之爬取豆瓣电影短评
查看>>
HDU 5510 Bazinga KMP
查看>>
[13年迁移]Firefox下margin-top问题
查看>>
Zookeeper常用命令 (转)
查看>>
Enterprise Library - Data Access Application Block 6.0.1304
查看>>
重构代码 —— 函数即变量(Replace temp with Query)
查看>>
Bootstrap栅格学习
查看>>
程序员的数学
查看>>
聚合与组合
查看>>
洛谷 P2089 烤鸡【DFS递归/10重枚举】
查看>>
我眼中的技术地图
查看>>
lc 145. Binary Tree Postorder Traversal
查看>>
在centos上开关tomcat
查看>>
无人值守安装linux系统
查看>>
黑马程序员——2 注释
查看>>
android dialog使用自定义布局 设置窗体大小位置
查看>>
ionic2+ 基础
查看>>