目录
URLConnection and HttpURLConnection
一个URLConnection 实例可以通过openConnection()方法创建如: URLConnection urlCon = url.openConnection();
如果协议是http://可以直接转成HttpURLConnection 如:HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
调用openConnection()并没有建立网络连接,只是返回实例,创建连接发生在调用connect() 或者通过实例读取header属性或者通过实例访问input stream / output stream.
简单例子如下:
String url = "https://google.com";
String filePath = "Google.html";
URL urlObj = new URL(url);
URLConnection urlCon = urlObj.openConnection();
InputStream inputStream = urlCon.getInputStream();
BufferedInputStream reader = new BufferedInputStream(inputStream);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
更多信息:
Java URLConnection and HttpURLConnection Examples
How to use Java URLConnection and HttpURLConnection
java11的HttpClient
简单样例如下:
public class HttpClientSynchronous {
private static final HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build();
public static void main(String[] args) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://httpbin.org/get"))
.setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// print response headers
HttpHeaders headers = response.headers();
headers.map().forEach((k, v) -> System.out.println(k + ":" + v));
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
}
}
更多信息:Java 11 HttpClient Examples
apache的HttpClient
添加依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
简单样例如下:
public class HttpClientExample1_1 {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet request = new HttpGet("https://httpbin.org/get");
// add request headers
request.addHeader("custom-key", "mkyong");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
CloseableHttpResponse response = httpClient.execute(request);
try {
// Get HttpResponse Status
System.out.println(response.getProtocolVersion()); // HTTP/1.1
System.out.println(response.getStatusLine().getStatusCode()); // 200
System.out.println(response.getStatusLine().getReasonPhrase()); // OK
System.out.println(response.getStatusLine().toString()); // HTTP/1.1 200 OK
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
更多信息:Apache HttpClient Examples
OkHttp
OkHttp is an HTTP client that’s efficient by default:
- HTTP/2 support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if HTTP/2 isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
添加依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
简单例子如下:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
更多信息:OkHttp
RestTemplate
As of Spring Framework 5, alongside the WebFlux stack, Spring introduced a new HTTP client called WebClient.
it’s a good idea to use WebClient. Moving forward, RestTemplate will be deprecated in future versions.
RestTemplate是一个执行HTTP请求的同步阻塞式工具类,它仅仅只是在 HTTP 客户端库(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基础上,封装了更加简单易用的模板方法 API,方便程序员利用已提供的模板方法发起网络请求和处理。一般spring项目直接使用,否则添加依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
或者
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
简单测试样例如下:
@Autowired
private RestTemplate restTemplate;
@GetMapping(path = "/sys")
public ResponseEntity<Object> queryMonitor() throws Exception {
String url = remoteUrl + "/coordinator/sys/getAll";
try {
List<Object> remoteList = restTemplate.getForObject(url, List.class);
Map<String, Object> localMap = localService.getServers();
if (remoteList != null) {
remoteList.add(0, localMap);
return new ResponseEntity<>(remoteList, HttpStatus.OK);
} else {
return new ResponseEntity<>(Collections.singletonList(localMap), HttpStatus.OK);
}
} catch (RestClientException e) {
if (e instanceof ResourceAccessException) {
throw new IOException("NodeManager connection err!");
}
throw e;
}
}
使用HttpURLConnection作为实现
@Configuration
public class RestTemplateConfig {
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(getClientHttpRequestFactory());
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
使用apache的HttpClient作为实现
@Configuration
public class RestTemplateConfig {
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(getClientHttpRequestFactory());
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
CloseableHttpClient client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.build();
return new HttpComponentsClientHttpRequestFactory(client);
}
}
使用OkHttp作为实现
@Configuration
public class RestTemplateConfig {
@ConditionalOnMissingBean(RestTemplate.class)
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(getClientHttpRequestFactory());
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
CloseableHttpClient client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.build();
return new HttpComponentsClientHttpRequestFactory(client);
}
}
请求数据
简单例子如下:
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl
= "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response
= restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
Assertions.assertNotNull(foo);
Assertions.assertEquals(foo.getName(), "bar");