从 Java 程序发出 HTTP 请求的最佳方式是什么?

bee*_*oak 5 java sql json http

我正在尝试使用一个小型 Java 程序发出 HTTPs 请求(发送 SQL 命令的纯文本)并尝试接收 JSON 数据。此功能是否已内置于 Java 中,还是需要外部包/库?

so-*_*ude 4

https://square.github.io/okhttp/是一个很好的http交互库。然后,如果需要,您可以使用 Jackson/Gson 解析对类型化对象的响应

用法

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
Run Code Online (Sandbox Code Playgroud)

行家:

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>2.4.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

或摇篮:

实施 'com.squareup.retrofit2:retrofit:2.4.0'

如果你想用巴顿坦克杀死一只蚂蚁,你有各种其他选择,例如 spring、netflix OSS - feign 客户端 + Ribbon 等

话虽这么说,首先,我会尝试一下 Kayaman 发布的内容,https://www.baeldung.com/java-9-http-client作为它的一个较少的依赖项。