HTTP网络协议

企业项目中总是会用到别人的接口,放一个HTTP网络协议备用把~上次传的不全 

public class HttpUtils {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType FROM_DATA = MediaType.parse("multipart/form-data");


    private static OkHttpClient okHttpClient;

    private synchronized static OkHttpClient getClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient();
        }
        return okHttpClient;
    }


    public static String getRequest(String url) throws IOException {
        return getRequestWithHeaders(url, null);
    }

    public static String getRequestWithHeaders(String url, Map headerMap) throws IOException {
        Request.Builder builder = new Request.Builder().url(url).get();
        if (headerMap != null) {
            builder.headers(Headers.of(headerMap));
        }
        return getClient().newCall(builder.build()).execute().body().string();
    }

    public static String postRequest(String url, JSONObject object) throws IOException {
        return postRequestWithHeaders(url, object, null);
    }

    public static String postRequestWithHeaders(String url, JSONObject object, Map headerMap) throws IOException {
        RequestBody body = RequestBody.create(JSON, object.toString());
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headerMap != null) {
            builder.headers(Headers.of(headerMap));
        }
        return getClient().newCall(builder.build()).execute().body().string();
    }

    public static  String sendFromDataPostRequest(String url, File file,String typeName)throws IOException{
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
        MultipartBody body = new MultipartBody.Builder()
                            .setType(FROM_DATA)
                            .addFormDataPart(typeName,"2.png",fileBody)
                            .build();
        Request request = new Request.Builder()
                            .post(body)
                            .url(url)
                            .build();

        return getClient().newCall(request).execute().body().string();



    }

}

 

你可能感兴趣的:(个人项目经验,工作笔记)