OKHttpUtils.java 2.89 KB

import okhttp3.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by youjie on 2018/4/27.
 */

public class OKHttpUtils {

    private static final String TAG = "HttpUtils";
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static void getAsycHttp(String url) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.method("GET",null);
        Request request = requestBuilder.build();
        Call mcall= mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {

            }

            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    String str = response.cacheResponse().toString();
                    System.out.println( "cache---" + str);
                } else {
                    response.body().string();
                    String str = response.networkResponse().toString();
                    System.out.println( "network---" + str);
                }
            }
        });
    }




    public static void commonPost(String url, String jsonString) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonString);
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS).build();
        Request request= null;
        request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {

            public void onFailure(Call call, IOException e) {
                System.out.println( "onFailure  :" + call.toString());
//                e.printStackTrace();
                System.exit(1);
            }


            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                if (cookies.size() > 0) {
                    String session = cookies.get(0);
                    String result = session.substring(0, session.indexOf(";"));
                    System.out.println( "cookies:" + result);
                }
                System.out.println("onResponse:" + str);
                System.exit(0);
            }
        });
    }

}