Apache HttpClient
Apache HttpClient библиотека реализующая набор функций для работы по протоколу HTTP.
Maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
GET:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://sarjsheff.ru/");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine());
response.getEntity().writeTo(System.out);
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
POST:
HttpPost httpPost = new HttpPost("http://sarjsheff.ru/");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
Сетевые настройки:
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
httpGet.setConfig(config);
Cookie и Session:
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
// connect
System.out.println(cookieStore.getCookies());