Java从URL作为字符串获取响应正文
示例
String getText(String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); //将标头添加到连接,或根据需要检查状态。 //处理发生的错误响应代码 int responseCode = conn.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(); return response.toString(); }
这将从指定的URL下载文本数据,并将其作为字符串返回。
工作原理:
首先,我们使用,HttpUrlConnection从URL创建一个。我们将此返回值转换为,因此可以访问诸如添加标头(例如UserAgent)或检查响应代码之类的内容。(此示例不执行此操作,但是很容易添加。)newURL(url).openConnection()UrlConnectionHttpUrlConnection
然后,InputStream根据响应代码创建(用于错误处理)
然后,创建一个BufferedReader允许我们InputStream从连接中读取文本的文件。
现在,我们将文本StringBuilder逐行追加到。
关闭InputStream,然后返回我们现在拥有的String。
笔记:
IoException如果失败(例如网络错误或没有Internet连接),则此方法将引发,并且如果给定的URL无效,还将未经检查MalformedUrlException。
它可用于从任何返回文本的URL读取,例如网页(HTML),返回JSON或XML的RESTAPI等。
另请参阅:用几行Java代码将URL读取为String。
用法:
很简单:
String text = getText(”http://example.com"); //对example.com中的文本(在本例中为HTML)进行处理。