Java–HttpClient
HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。
通過HttpClient可以模擬發出http請求,支持各種請求如get\post\delete等http協議。
也可以做爬蟲。
使用Get請求測試一下:
HttpGet請求
通過Get請求獲取到響應回來的響應體數據
public void test() throws Exception{
//創建一個客戶端
CloseableHttpClient client = HttpClients.createDefault();
//創建一個Get請求
HttpGet httpGet = new HttpGet("http://jsonplaceholder.typicode.com/users");
//通過客戶端執行該請求,返回一個響應
CloseableHttpResponse response = client.execute(httpGet);
//獲取響應體對象
HttpEntity entity = response.getEntity();
//獲取響應體內容
InputStream content = entity.getContent();
byte[] bytes=new byte[102400];
int read = content.read(bytes);
//輸出到控制檯
System.out.println(new String(bytes,0,read));
//關閉掉所有流
content.close();
response.close();
client.close();
}
//響應回來的Json數據
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
各種請求都是繼承自HttpRequestBase,HttpRequestBase再向上繼承。
基本上只是方法名字不同。
@NotThreadSafe
public class HttpGet extends HttpRequestBase {
public final static String METHOD_NAME = "GET";
public HttpGet() {
super();
}
public HttpGet(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpGet(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
爬蟲
HttpClient也可以用於爬蟲,如:
將獲取的網絡資源輸出到文件中。
//傳入url,以及資源路徑
public static void getUrl(String url,String path) throws Exception{
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
//打印流
PrintStream printStream=new PrintStream(path);
int len;
while((len=inputStream.read())!=-1){
printStream.write(len);
}
inputStream.close();
printStream.close();
response.close();
client.close();
}
@Test
public void test2() throws Exception{
getUrl("http://jsonplaceholder.typicode.com/users","./get.json");
}