okHttp工具类,实现get和post

public class HttpUtils {

private HttpUtils() {

}

public static String getHttpInfo(String url, Map<String, String> params) throws URISyntaxException, IOException {

    OkHttpClient httpClient = new OkHttpClient();
    URIBuilder uriBuilder = new URIBuilder(url);
    for (Map.Entry<String, String> param : params.entrySet()) {

        uriBuilder.addParameter(param.getKey(), param.getValue());
    }

    Request request = new Request.Builder()
            .url(uriBuilder.build().toURL())
            .build();

    Response response = httpClient.newCall(request).execute();
    return response.body().string();
}

public static String postHttpInfo(String url, Map<String, String> params) throws IOException {

    OkHttpClient httpClient = new OkHttpClient();

    FormEncodingBuilder form = new FormEncodingBuilder();
    for(Map.Entry<String, String> param : params.entrySet()) {

        form.add(param.getKey(), param.getValue());
    }
    Request request = new Request.Builder()
            .url(url)
            .post(form.build())
            .build();
    Response response = httpClient.newCall(request).execute();
    return response.body().string();
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp 是一款基于 Java 的 HTTP 客户端,它使用了连接池、异步 IO 和拦截器等技术来提高性能和灵活性。下面是一个基于 OkHttp 的 Java 工具类,可以用于发送 HTTP 请求和接收响应: ```java import okhttp3.*; import java.io.IOException; public class OkHttpUtils { private static final OkHttpClient client = new OkHttpClient(); public static String get(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } return response.body().string(); } } public static String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(json, MediaType.get("application/json")); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } return response.body().string(); } } } ``` 在上面的代码中,我们使用了 OkHttp 的 `OkHttpClient` 类来创建一个 HTTP 客户端,然后定义了两个方法 `get` 和 `post` 来发送 GET 和 POST 请求。在 `get` 方法中,我们使用 `Request.Builder` 类来构建一个 GET 请求,并使用 `client.newCall(request).execute()` 方法来发送请求并接收响应。在 `post` 方法中,我们使用 `RequestBody` 类来创建一个 JSON 请求体,并将其传递给 `Request.Builder` 类的 `post` 方法来构建一个 POST 请求。最后,我们使用相同的方式发送请求并接收响应。注意,为了避免资源泄漏,我们使用了 try-with-resources 语句来自动关闭响应体。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值