Maven: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> Gradle: groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com/api/resource"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); } catch (IOException e) { e.printStackTrace(); } HttpPost httpPost = new HttpPost("http://example.com/api/resource"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); } catch (IOException e) { e.printStackTrace(); } httpGet.setHeader("User-Agent", "Mozilla/5.0"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); httpGet.setConfig(requestConfig);


上一篇:
下一篇:
切换中文