本文主要是介绍jakarta 实现 HttpClient,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
正在使用quarkus开发项目。使用jdk17,过去的HttpClient不能用了,经过一番周折,重新实现了HttpClient简单版,代码如下
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Form;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;@ApplicationScoped
public class HttpClient {private Client client;public HttpClient() {this.client = ClientBuilder.newClient();}public Response get(String uri, Map<String, String> queryParams) {WebTarget target = client.target(uri);for (Map.Entry<String, String> entry : queryParams.entrySet()) {target = target.queryParam(entry.getKey(), entry.getValue());}return target.request().get();}public Response post(String uri, Map<String, String> bodyParams) {WebTarget target = client.target(uri);Form form = new Form();for (Map.Entry<String, String> entry : bodyParams.entrySet()) {form.param(entry.getKey(), entry.getValue());}return target.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));}// 其他 HTTP 方法...public void close() {client.close();}
}
这篇关于jakarta 实现 HttpClient的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!