Kal*_*pak 200
如果要流式传输任何网页,可以使用以下方法.
import java.io.*;
import java.net.*;
public class c {
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static void main(String[] args) throws Exception
{
System.out.println(getHTML(args[0]));
}
}
Run Code Online (Sandbox Code Playgroud)
cle*_*tus 56
从技术上讲,你可以使用直接TCP套接字.但我不推荐它.我强烈建议您使用Apache HttpClient.在其最简单的形式:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
Run Code Online (Sandbox Code Playgroud)
这是一个更完整的例子.
HyL*_*ian 35
如果您不想使用外部库,则可以使用标准Java API中的URL和URLConnection类.
示例如下所示:
String urlString = "http://wherever.com/someAction?param1=value1¶m2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
355895 次 |
最近记录: |