Java okHttp清求Utils

清求实体

@Data
@ToString
public class Params {

    /**
     * 清求参数
     */
    private String parameter;
}

清求 工具类

public class OkHttpUtils {

    private static final OkHttpClient CLIENT = new OkHttpClient().newBuilder()
            .build();
    /**
     * API
     */
    private static final String API = "https://api.com";


    /***
     * application/json
     * @return
     * @throws Exception
     */
    public static JSONObject json(Params params) throws Exception {
        MediaType mediaType = MediaType.parse("application/json");
        String json = JSON.toJSONString(params);
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(API)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                //.addHeader("parameter",params.getParameter())  //清求头有数据直接这样加
                .build();
        Response response = CLIENT.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("清求响应:"+result);
        return JSONObject.parseObject(result);
    }

    /***
     * application/x-www-form-urlencoded
     * @return
     * @throws IOException
     */
    public static JSONObject urlencoded(Params params) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String json = "parameter=" + params.getParameter();
        System.out.print("===========请求:{}" + json);
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(API)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = CLIENT.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("清求响应:"+result);
        return JSONObject.parseObject(result);
    }

    /***
     * form-data
     * @return
     * @throws IOException
     */
    public static JSONObject formData(Params params) throws IOException {
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("parameter",params.getParameter())
                .build();
        Request request = new Request.Builder()
                .url(API)
                .method("POST", body)
                .build();
        Response response = CLIENT.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("清求响应:"+result);
        return JSONObject.parseObject(result);
    }

    /***
     * query params
     * @return
     * @throws IOException
     */
    public static JSONObject params(Params params) throws IOException {
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("parameter", params.getParameter());
        String json =API +"?"+ getSignContent(paramsMap);
        System.out.println("请求json :" + json);
        MediaType mediaType = MediaType.parse("text/plain");
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, "{}");
        Request request = new Request.Builder()
                .url(json)
                .method("POST", body)
                .build();
        Response response = CLIENT.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("清求响应:"+result);
        return JSONObject.parseObject(result);
    }


    /**
     * GET
     * @param params
     * @return
     * @throws Exception
     */
    public static JSONObject get(Params params) throws Exception {
        String json = API + "?parameter=" + params.getParameter();
        System.out.println("请求json:"+ json);
        Request request = new Request.Builder()
                .url(json)
                .method("GET", null)
                .build();
        Response response = CLIENT.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("清求响应:"+result);
        return JSONObject.parseObject(result);
    }

    /**
     * 格式化拼接参数
     * @param sortedParams
     * @return
     */
    public static String getSignContent(Map<String, String> sortedParams) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            Object value = sortedParams.get(key);
            if (value != null && StringUtils.isNotEmpty(value.toString())) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                index++;
            }
        }
        return content.toString();
    }

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值