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<String, String> 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<String, String> 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();



    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值