httpClient

public static void main(String[] args) throws Exception{
		//創建httpClient實例
		CloseableHttpClient httpClient = HttpClients.createDefault();	
		
		//創建httpGet實例
		HttpGet httpGet = new HttpGet("https://www.baidu.com/");	
		
		//設置請求頭信息,這是chrome的請求頭信息
		httpGet.setHeader("User-Agent", "這是請求頭信息");		

		//設置代理
		new().httpProxySet(httpGet);
		
		//執行http協議的get請求
		CloseableHttpResponse response = httpClient.execute(httpGet);	
		
		//返回服務器對你的狀態,如HTTP/1.1 200 OK,
		//加.getStusCode後只返回數字(如:200),便於分析
		System.out.println("status:" + response.getStatusLine().getStatusCode());
		
		HttpEntity entity = response.getEntity();	//獲得返回實體
		
		//下載圖片
		new().downloadPicture(httpEntity);

		//獲取響應類型:ContentType,特徵識別
		System.out.println("ContentType:" + entity.getContentType().getValue()); 
		
		//查看網頁內容
		System.out.println("網頁內容是:" + EntityUtils.toString(entity,"utf-8"));
		
		response.close();
		httpClient.close();
	}

	//設置代理
	public void httpProxySet(HttpGet httpGet) {
		HttpHost proxy = new HttpHost("222.189.190.58", 9999);
		RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
		httpGet.setConfig(config);
	}

	//下載圖片
	public void downloadPicture(HttpEntity entity) throws Exception{
		/*打開輸入流,將圖片放在內存中,然後用copyToFile方法將內存中的內容寫入到想要的地方,
		實現一個簡單的粘貼複製*/
		if(entity != null) {
			System.out.println("COntenType:" + entity.getContentType().getValue());
			//打開輸入流
			InputStream inputStream = entity.getContent();
			//將輸入流寫入到文件中
			FileUtils.copyToFile(inputStream,new File("D://ZCQ//copy.jpg"));
		}
	}
  • httpclient請求Get請求帶參數
void method(){
		CloseableHttpClient httpClient = HttpClients.createDefault();

        //設置請求的地址是:https://search.bilibili.com/all?keyword=httpclient
        //創建UriBulider
        URIBuilder uriBuilder = new URIBuilder("https://search.bilibili.com/all");

        //設置參數
        uriBuilder.setParameter("keyword","httpclient")
        			.setParameter("param1","value1")
        			.setParameter("param2","value2");

        //創建HttpGet對象,設置uri訪問地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

		//再參照httpclient,即可
		}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章