要使用HttpClient来获取网页,首先需要在项目中导入HttpClient库。以下是一个简单的示例代码:

java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.example.com");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
}
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面的代码会向"https://www.example.com"发送一个GET请求,并将获取到的网页内容输出到控制台。请确保在项目中包含HttpClient库的依赖。

查看详情

查看详情