Java中如何使用HttpURLConnection请求指定URL并返回字符串呢?
下文笔者讲述HttpURLConnection获取请求URL并返回字符串的方法分享,如下所示
编写HttpURLConnection读取URL的示例
实现思路: 1.使用URL对象的openConnection即可返回一个HttpURLConnection对象 2.使用HttpURLConnection对象的getInputStream()方法即可返回读取的BufferedReader例:
编写HttpURLConnection读取URL的示例
private static String readUrl(String urlvalue) { String inputLine = ""; try { URL url = new URL(urlvalue); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection .getInputStream())); inputLine = in.readLine().toString(); } catch (Exception e) { e.printStackTrace(); inputLine = ""; } return inputLine; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。