<body>
<form action="/。。。。" id="form1">
<input type="hidden" name="indexUrl" id="indexUrl">
<a href="javascript:void(0)" onclick="goTo()">URL</a>
</form>
</body>
<script type="text/javascript">
function goTo(){
var form = document.getElementById("form1")
var url = location.href
var indexUrl = document.getElementById("indexUrl")
indexUrl.value = url
form.submit()
}
</script>
servlet的doPost方法:
String indexUrl = request.getParameter("indexUrl")
URL url = new URL(indexUrl)
InputStream is = url.openConnection().getInputStream()
byte[] bs = new byte[9999]
int len = 0
while((len = is.read(bs, 0, 9999))!=-1){
System.out.write(bs, 0, len)
}
is.close()
还可以用专门获取网页的JAR包,好像是jsoap?上面的代码没有考虑转码的问题。如果是中文可能出现乱码,注意要统一编码格式。
------------------------------------------------------
修改了一下servlet的doPost方法,解决编码问题。我的页面是utf-8编码。
String indexUrl = request.getParameter("indexUrl")
URL url = new URL(indexUrl)
InputStream is = url.openStream()
// InputStream is = url.openConnection().getInputStream()
InputStreamReader isr = new InputStreamReader(is,"utf-8")
char[] cs = new char[9999]
while(isr.read(cs, 0, 9999)!=-1){
System.out.print(cs)
}
is.close()
import java.io.BufferedReaderimport java.io.IOException
import java.io.InputStreamReader
import java.net.URL
import java.net.URLConnection
import java.util.Scanner
public class UrlReader {
public static String read(String url) throws IOException {
StringBuffer html = new StringBuffer()
URL addrUrl = null
URLConnection urlConn = null
BufferedReader br = null
try {
addrUrl = new URL(url)
urlConn = addrUrl.openConnection()
br = new BufferedReader(new InputStreamReader(urlConn
.getInputStream()))
String buf = null
while ((buf = br.readLine()) != null) {
html.append(buf + "\r\n")
}
} finally {
if(br != null){
br.close()
}
}
return html.toString()
}
public static void main(String[] args){
System.out.println("请输入url(e.g http://www.baidu.com)")
Scanner scan = new Scanner(System.in)
String url = scan.next()
String html = null
try {
html = UrlReader.read(url)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
System.out.println(html)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)