httpclient发请求
第一中实现:
1. 创建mavern项目并在pom.xml中添加依赖
org.apache.httpcomponents httpclient4.5.2
2. get请求
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
import java.io.IOException;
public class HttpGetNovars {
public static void main(String[] args) throws IOException {
String url = "https://www.baidu.com/";
HttpGet get = new HttpGet(url);
CloseableHttpClient hc = HttpClients.createDefault();
CloseableHttpResponse response = hc.execute(get);
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
}
}
第二种实现
1. 导入依赖
org.apache.httpcomponents.client5 httpclient55.0.1
2. get请求
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import java.io.IOException;
public class httpClientDemo1 {
public static void main(String[] args) throws IOException, ParseException {
String url = "https://www.baidu.com/";
HttpGet get = new HttpGet(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(get);
int code = response.getCode();
System.out.println(code);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
Header[] headers = response.getHeaders();
for (Header header:headers){
System.out.println(header.getName());
System.out.println(header.getValue());
}
}
}



