gpt4 book ai didi

java - 如何在网页中搜索字词

转载 作者:行者123 更新时间:2023-11-30 11:56:05 25 4
gpt4 key购买 nike

如何在给定 url 说“www.microsoft.com”的网页中搜索是否存在该词。我是否需要下载此网页才能执行此搜索?

最佳答案

你只需要在网页上发出http请求并抓取它的所有内容,然后你就可以在其中搜索必要的词,下面的代码可能会帮助你这样做。

 public static void main(String[] args) {
try {
URL url;
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;

// Build request body
String body =
"fName=" + URLEncoder.encode("Atli", "UTF-8") +
"&lName=" + URLEncoder.encode("Þór", "UTF-8");

// Create connection
url = new URL("http://www.example.com");
urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""+ body.length());

// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
inStream = new DataInputStream(urlConnection.getInputStream());

// Send request
outStream.writeBytes(body);
outStream.flush();
outStream.close();

// Get Response
// - For debugging purposes only!
String buffer;
while((buffer = inStream.readLine()) != null) {
System.out.println(buffer);
}

// Close I/O streams
inStream.close();
outStream.close();
}
catch(Exception ex) {
System.out.println("Exception cought:\n"+ ex.toString());
}
}

关于java - 如何在网页中搜索字词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4676994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com