首页 > 编程语言 > 详细

java成神之——HttpURLConnection访问api

时间:2018-10-07 16:19:54      阅读:151      评论:0      收藏:0      [点我收藏+]

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<String, List<String>> map = connection.getHeaderFields();
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, List<String>>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
    Map.Entry<String, List<String>> 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成神的系列文章之一

如果你想知道,但是本文没有的,请下方留言

我会第一时间总结出来并发布填充到本文

java成神之——HttpURLConnection访问api

原文:https://www.cnblogs.com/ye-hcj/p/9750367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!