非常简单的OKhttp封装工具类

Map<String, String> httpParams =  new HashMap<>();
httpParams.put("devicecode", "343257687798790");
com.tangzy.myokhttp.async.bean.ResponseResult responseResult = AsyncOkHttpManager.asyncRequest("https://www.baidu.com" ,httpParams, false);

String status = responseResult.getStatus();
Response response = responseResult.getResponse();
textView1.setText(response.message());
responseResult.getErrorMsg();
好的,以下是一个简单的封装 OkHttp工具类: ```java import okhttp3.*; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Map; @Component public class OkHttpUtils { private OkHttpClient client = new OkHttpClient(); /** * 发送 GET 请求 * * @param url 请求 URL * @return 响应结果 * @throws IOException IO 异常 */ public String get(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } /** * 发送 POST 请求 * * @param url 请求 URL * @param params 请求参数 * @return 响应结果 * @throws IOException IO 异常 */ public String post(String url, Map<String, String> params) throws IOException { FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } } ``` 使用时,只需要在 Spring Boot 应用中注入该工具类即可: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController public class TestController { @Autowired private OkHttpUtils okHttpUtils; @GetMapping("/test") public String test() throws IOException { String url = "http://example.com"; String result = okHttpUtils.get(url); return result; } @GetMapping("/testParam") public String testParam() throws IOException { String url = "http://example.com"; Map<String, String> params = new HashMap<>(); params.put("param1", "value1"); params.put("param2", "value2"); String result = okHttpUtils.post(url, params); return result; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值