public class HttpConnectionGet { public HttpConnectionGet() { } // public static byte[] doGetRequest(String path) { InputStream inputStream = null; byte[] outdata = null; URL url = null; HttpURLConnection connection; try { url = new URL(path); } catch (MalformedURLException e) { e.printStackTrace(); } if (url != null) { try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000); connection.setDoInput(true); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == 200) inputStream = connection.getInputStream(); /// ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; while ((len = inputStream.read(data)) != -1) outputStream.write(data, 0, len); outdata = outputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return outdata; } }
HttpConnection底层代码实现Get方法
最新推荐文章于 2023-04-06 09:51:51 发布
本文档详细介绍了HttpConnectionGet类中实现GET请求的过程。通过创建URL对象,建立HttpURLConnection连接,设置超时和请求方法,获取响应码,读取输入流并将数据转化为字节数组,展示了如何从指定路径获取HTTP资源。
摘要由CSDN通过智能技术生成