HttpClient--入門
1 獲取網頁程式碼
public static void main(String[] args){
CloseableHttpClient httpClient = HttpClients.createDefault();//建立httpclient例項
HttpGet httpGet=new HttpGet("http://www.open1111.com");
CloseableHttpResponse response=null;
try {
response= httpClient.execute(httpGet);
} catch (ClientProtocolException e) {//協議異常
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity=response.getEntity();
try {
String string = EntityUtils.toString(entity,"utf-8");
System.out.println(string);
} catch (ParseException e) {//解析異常
e.printStackTrace();
} catch (IOException e) {//IO異常
e.printStackTrace();
}
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2 獲取相關資訊
2.1 獲取返回的狀態資訊:
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println("Status:"+response.getStatusLine().getStatusCode());
2.2 獲取返回頭資訊中ContentType的值
System.out.println(entity.getContentType().getValue());
3 獲取圖片
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();// 建立httpclient例項
HttpGet httpGet = new HttpGet("https://www.baidu.com/img/bd_logo1.png");
//設定請求頭資訊User-Agent模擬瀏覽器
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/56.0");
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("ContentType:"+entity.getContentType().getValue());
InputStream content = entity.getContent();
//複製檔案到本地
//org.codehaus.plexus.util.FileUtils.copyURLToFile(new URL("https://www.baidu.com/img/bd_logo1.png"), new File("D:/image.png"));
FileUtils.copyToFile(content,new File("D:/image.png"));
}
response.close();
httpClient.close();
System.out.println("run over");
}
相關文章
- HttpClient--傳送請求HTTPclient
- 入門入門入門 MySQL命名行MySql
- 如何入CTF的“門”?——所謂入門就是入門
- 何入CTF的“門”?——所謂入門就是入門
- scala 從入門到入門+
- makefile從入門到入門
- ACM入門之新手入門ACM
- 【小入門】react極簡入門React
- gRPC(二)入門:Protobuf入門RPC
- 《Flutter 入門經典》之“Flutter 入門 ”Flutter
- 新手入門,webpack入門詳細教程Web
- Android入門教程 | RecyclerView使用入門AndroidView
- linux新手入門――shell入門(轉)Linux
- MyBatis從入門到精通(一):MyBatis入門MyBatis
- SqlSugar ORM 入門到精通【一】入門篇SqlSugarORM
- Storm入門指南第二章 入門ORM
- VUE入門Vue
- MyBatis 入門MyBatis
- CSS 入門CSS
- JavaScript 入門JavaScript
- Nginx 入門Nginx
- RabbitMQ入門MQ
- GitHub入門Github
- Redis 入門Redis
- PostgreSQL 入門SQL
- Prometheus 入門Prometheus
- VuePress 入門Vue
- Tableau入門
- WebSocket 入門Web
- Webpack 入門Web
- UML入門
- nlp入門
- gulp入門
- Dubbo 入門
- AVFoundation 入門
- Nginx入門Nginx
- Redux入門Redux
- angular入門Angular