1、HttpURLConnection 继承 URLConnection
2、HttpURLConnection较URLConnection多了获取状态码的方法 getResponseCode(),使用的时候要转换
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;然后在刷新写入流后才能使用 getResponseCode()
3、URLConnection 可以走邮件、文件传输协议,而HttpURLConnection 就单指浏览器的HTTP协议
示例代码
PrintWriter write = null; BufferedReader reader = null; try { URL uri = new URL(url); URLConnection request = uri.openConnection(); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection)request; // 发送POST请求必须设置如下两行 connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(2000); connection.setReadTimeout(2000); // 获取URLConnection对象对应的输出流 write = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), encoding)); write.print(postData); // 发送post数据 write.flush(); logger.info("http返回码:"+connection.getResponseCode()); // 定义BufferedReader输入流来读取URL的响应 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); String line = ""; StringBuilder contentBuf = new StringBuilder(); while ((line = reader.readLine()) != null) { contentBuf.append(line); } return contentBuf.toString(); } catch (Exception e) { e.printStackTrace(); logger.info("http请求异常:"+e.getMessage()); logger.info("http请求异常:"+e.toString()); } finally { try { if (write != null) { write.close(); } if (reader != null) { reader.close(); } } catch (Exception ex) { } }
参考博文:
https://www.cnblogs.com/sun7897/p/9993657.html