okhttp3请求笔记

2023-01-31 02:01:04 请求 笔记 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();
    }

    
    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);
        }
    }

    
    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);
        }
    }

    
    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();
        }

    }

}

相关文章