- 简介
- 同步
- 异步
- 结果
- HTTP 客户端是在 Java 11 中添加的。它可用于通过网络请求 HTTP 资源。它支持 HTTP/1.1和HTTP/2,包括同步和异步编程模型,将请求和响应主体作为反应流处理,并遵循熟悉的构建器模式。
- 代码
public static void main(String[] args) { // HttpClient client = HttpClient.newBuilder() // .version(Version.HTTP_2) // .followRedirects(Redirect.SAME_PROTOCOL) // .proxy(ProxySelector.of(new InetSocketAddress("www-proxy.com", 8080))) // .authenticator(Authenticator.getDefault()) // .build(); // HttpRequest request = HttpRequest.newBuilder() // .uri(URI.create("http://openjdk.java.net/")) // .timeout(Duration.ofMinutes(1)) // .header("Content-Type", "application/json") // .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("file.json"))) // .build(); // 静态方法获取客户端HttpClient HttpClient httpClient = HttpClient.newHttpClient(); // 静态方法创建 HttpRequest request = HttpRequest.newBuilder(URI.create("http://xxx.xxx.xx.xx:xxxx/api/customer/v1/info/find_customer_info_list")).build(); // 生成BodyHandler BodyHandler异步responseBodyHandler = HttpResponse.BodyHandlers.ofString(); // 发送 得到HttpResponse try { HttpResponse response = httpClient.send(request, responseBodyHandler); String body = response.body(); System.out.println(body); } catch (Exception e) { e.printStackTrace(); } }
- 代码
public static void main(String[] args) { // 获取客户端HttpClient HttpClient httpClient = HttpClient.newHttpClient(); // 生成HttpRequest HttpRequest request = HttpRequest.newBuilder(URI.create("http://xxx.xxx.xx.xx:xxxx/api/customer/v1/info/find_customer_info_list")).build(); // 生成BodyHandler BodyHandler结果responseBodyHandler = HttpResponse.BodyHandlers.ofString(); // 发送 得到HttpResponse try { CompletableFuture > responseAsync = httpClient.sendAsync(request, responseBodyHandler); HttpResponse response = responseAsync.get(); String body = response.body(); int i = response.statusCode(); System.out.println(body); System.out.println("status: "+i); } catch (Exception e) { e.printStackTrace(); } }
{ "code": 0, "data": [ { "id": 3, "sender": "郭总", "phone": "133******89", "consignee": "郭林枝", "customer_name": "***科技开发有限公司", "delivery_address": "******园区同业路5号 内蒙古林科技 院内", "bank_name": "包头市支行", "bank_account": "1234567899874632120", "tax_number": "9136********492L" }, { "id": 1, "sender": "陈工", "phone": "18******90", "consignee": "陈总", "customer_name": "****傲表计有限公司", "delivery_address": "******门基地", "bank_name": "杭州银行蒋村支行", "bank_account": "3301**************09", "tax_number": "9135*********4801L" } ], "msg": null } status: 200
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)