java成神之——HttpURLConnection访问api
2021-05-15 18:30
标签:ons val epo map null java current while inpu java成神之——HttpURLConnection访问api 标签:ons val epo map null java current while inpu 原文地址:https://www.cnblogs.com/ye-hcj/p/9750367.html
HttpURLConnection
访问get资源
HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();
int responseCode = connection.getResponseCode();
InputStream inputStream;
if (200
访问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
获取状态码
HttpURLConnection connection = (HttpURLConnection)new URL("http://ip/test").openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
connection.disconnect();
结语
本文章是java成神的系列文章之一
如果你想知道,但是本文没有的,请下方留言
我会第一时间总结出来并发布填充到本文
下一篇:java成神之——文件IO
文章标题:java成神之——HttpURLConnection访问api
文章链接:http://soscw.com/index.php/essay/85911.html