All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.foreveross.springboot.dubbo.utils.OkHttpClientUtils Maven / Gradle / Ivy

There is a newer version: 2.3.8
Show newest version
package com.foreveross.springboot.dubbo.utils;

import com.squareup.okhttp.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenShaoWen on 2016/6/21.
 *
 * rest Client工具类
 */
public class OkHttpClientUtils {

    private final static Logger logger = LoggerFactory.getLogger(OkHttpClientUtils.class);

    private final static OkHttpClient okHttpClient = new OkHttpClient();

    static {
        okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    }

    private final static ObjectMapper objectMapper = new ObjectMapper();


    public static Map getFromKong(String target) throws IOException {
        if (target != null && target != "") {
            Request request = new Request.Builder().url(target).build();
            Response response = okHttpClient.newCall(request).execute();
            String resuit = response.body().string();
            return objectMapper.readValue(resuit, Map.class);
        }
        return (Map) (new HashMap()).put("error", "params exception");
    }


    public static Map postToKong(Map map, String target) throws IOException {
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        if (map != null && target != null) {
            RequestBody body = RequestBody.create(json, objectMapper.writeValueAsString(map));
            Request request = new Request.Builder().url(target).post(body).build();
            Response response = okHttpClient.newCall(request).execute();
            String resuit = response.body().string();
            return objectMapper.readValue(resuit, Map.class);
        }
        return (Map) (new HashMap()).put("error", "params exception");
    }


    public static boolean deleteFromKong(String target) throws IOException {
        if (target != null && target != "") {
            Request request = new Request.Builder().url(target).delete().build();
            Response response = okHttpClient.newCall(request).execute();
            String status = String.valueOf(response.code());
            if (status.matches("^2.*")) {
                return true;
            }
            return false;
        }
        return false;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy