我正在尝试使用小型 Java 程序发出 HTTPs 请求(发送 SQL 命令的纯文本)并尝试接收 JSON 数据。此功能是否已内置到 Java 中,或者我是否需要外部包/库?
最佳答案
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(); }
专家:
<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.4.0</version> </dependency>
或 Gradle :
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
如果你想用 Patton Tank 杀死一只 Ant ,你有各种其他选择,比如 spring、netflix OSS - feign client + ribbon 等
也就是说,首先,我会尝试 Kayaman 发布的内容,https://www.baeldung.com/java-9-http-client作为它的一个较少的依赖。
关于java - 从 Java 程序发出 HTTP 请求的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51935499/