okhttp3请求笔记

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.2.0</version>
        </dependency>
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    private static OkHttpClient client = null;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static void init(){
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20,TimeUnit.SECONDS)
                .build();
    }

    /**
     *
     * MethodName : executeGet
     * @Description : get方式链接url获取返回String结果
     * @param url 请求链接
     * @return 返回结果字符串
     * @throws Exception
     * @author
     * @date: 2017-7-13 上午9:12:55
     */
    public static String executeGet(String url) throws Exception {
        if (url == null || "".equals(url.trim())) {
            throw new Exception("null url");
        }
        Request request = new Request.Builder().url(url).build();
        init();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * MethodName : executePost
     * @Description : post方式链接url获取返回String结果
     * @param url 请求路径
     * @param params 参数map
     * @return 返回结果字符串
     * @throws Exception
     * @author
     * @date: 2017-12-14 上午10:12:55
     */
    public static String executePost(String url, Map<String,String> params) throws Exception {
        if (url == null || "".equals(url.trim())) {
            throw new Exception("null url");
        }
        FormBody.Builder formBody = new FormBody.Builder();
        if (params != null && params.size() > 0 ){
            for (String key : params.keySet()) {
                formBody.add(key,params.get(key));
            }
        }
        Request requestPost = new Request.Builder()
                .url(url)
                .post(formBody.build())
                .build();
        init();
        Response response = client.newCall(requestPost).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * POST请求,参数为json
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String postJson(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
//                .header("键", "值")
//                .header("键", "值")
                .post(body)
                .build();
        init();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static void main(String[] args) {
        try {
            String res =  postJson("http://",
                    "{\"groupNoList\":[\"g1766149\"]}");
            System.out.println(res);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}

猜你喜欢

转载自blog.51cto.com/357712148/2169886