HttpURLConnection
简单来说,HttpURLConnection 是 Java 提供的发起 HTTP 请求的基础类库,提供了 HTTP 请求的基本功能,不过封装的比较少,在使用时很多内容都需要自己设置,也需要自己处理请求流和响应流。
1.获取连接
URL url = new URL("http//ip:port/xxx");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = (HttpURLConnection)urlConnection;
2.参数设置
// 设置连接超时时间, 值必须大于0,设置为0表示不超时 单位为“毫秒”
connection.setConnectTimeout(30000);
// 设置读超时时间, 值必须大于0,设置为0表示不超时 单位毫秒
connection.setReadTimeout(60000);
// 设置为 GET 请求,
connection.setRequestMethod("GET");
// 设置请求类型为 application/json
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 设置可接受的数据类型
connection.setRequestProperty("Accept", "*/*");
// 设置保持长链接
connection.setRequestProperty("Connection", "Keep-Alive");
// 设置自定义头 Token
connection.setRequestProperty("Token", "xxxxx");
// 设置不使用缓存, 默认为 true 使用缓存
connection.setUseCaches(false);
// 设置单次请求是否支持重定向,默认为 setFollowRedirects 方法设置的值
connection.setInstanceFollowRedirects(false);
// 设置是否进行重定向,注意此处为 静态方法,表示所有的请求都不支持重定向,默认为true
HttpURLConnection.setFollowRedirects(false);
3.连接
// 调用打开连接, 调用此方法,只是建立一个连接,并不会发送数据。
connection.connect();
// 获取输出流
connection.getOutputStream();
// 获取输入流
connection.getInputStream();
4.接收数据
// 获取请求状态,此状态即为 HTTP 请求的状态 200:成功,404:找不到资源 等
int responseCode = connection.getResponseCode();
// 获取请求描述信息
String msg = connection.getResponseMessage();
// 获取输入流
InputStream inputStream = connection.getInputStream();
// 定义一个临时字节输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// 开始读取数据
byte[] buffer = new byte[256];
int len = 0;
while ((len = inputStream.read(buffer)) > 0){
baos.write(buffer,0, len);
}
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
} finally {
// 关闭输入、输出流
inputStream.close();
baos.close();
}
5.发送数据
// 要发送的数据
String connect = "我是一个POST请求数据";
// 因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
connection.setDoOutput(true);
// 从连接中获取 输出流对象
OutputStream os = connection.getOutputStream();
// 往输出流中写数据
os.write(connect.getBytes(StandardCharsets.UTF_8));
// 冲刷 并 关闭输出流
os.flush();
os.close();
测试
try {
URL url=new URL("http://httpbin.org/get");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode);
InputStream inputStream = urlConnection.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] bytes=new byte[1024];
int len=0;
while (((len =inputStream.read(bytes)) != -1)) {
String s = new String(bytes, 0, len);
System.out.println(s);
}
inputStream.close();
bout.close();
} catch (Exception e) {
throw new RuntimeException(e);
}