HttpClient与OkHttpClient的区别

一、HttpClient简介

HttpClient被用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

特性:

  1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1
  2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
  3. 支持HTTPS协议。
  4. 通过Http代理建立透明的连接。
  5. 利用CONNECT方法通过Http代理建立隧道的https连接。
  6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
  7. 插件式的自定义认证方案。
  8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
  9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
  10. 自动处理Set-Cookie中的Cookie。
  11. 插件式的自定义Cookie策略。
  12. Request的输出流可以避免流中内容直接缓冲到socket服务器。
  13. Response的输入流可以有效的从socket服务器直接读取相应内容。
  14. 在http1.0和http1.1中利用KeepAlive保持持久连接。
  15. 直接获取服务器发送的response code和 headers。
  16. 设置连接超时的能力。
  17. 实验性的支持http1.1 response caching。
  18. 源代码基于Apache License 可免费获取。

使用步骤:

  1. 创建HttpClient对象
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数
  4. 调用HttpClient对象的execute(HttpUriRequest request)方法发送请求,该方法返回一个HttpResponse
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容
  6. 释放连接。无论执行方法是否成功,都必须释放连接

使用实例:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.rigel.rap.project.bo.*;
import com.test.testmanagement.model.HttpinvokerInterfaceInfos;
import com.test.testmanagement.model.MockRecord;
import com.test.testmanagement.model.umeapi.mybean.C2sParameterClientOfVue;
import com.test.testmanagement.model.umeapi.mybean.Group;
import com.test.testmanagement.model.umeapi.mybean.GroupProject;
import com.test.testmanagement.service.HttpinvokerInterfaceInfosService;
import com.test.testmanagement.service.UmeAPIGroupProjectService;
import com.test.testmanagement.service.UmeAPIGroupService;
import com.test.testmanagement.service.UmeAPIMockService;
import com.test.testmanagement.utils.DesUtilTool;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/api/umeapi")
public class UmeAPIController {

    @Autowired
    UmeAPIGroupService umeAPIGroupService;

    @Autowired
    UmeAPIGroupProjectService umeAPIGroupProjectService;

    @Autowired
    HttpinvokerInterfaceInfosService httpinvokerInterfaceInfosService;

    @Autowired
    UmeAPIMockService umeAPIMockService;

    @RequestMapping(value = "/des", method = RequestMethod.POST)
    public String desUtil(@RequestBody JSONObject requestBodyParameters) throws Exception {
        System.out.println("requestBodyParameters:"+requestBodyParameters);
        //获取请求json串,并转换成string类型
        JSONObject requestBodyParam = requestBodyParameters.getJSONObject("request");
        System.out.println("requestBodyParam:" + requestBodyParam);
        String requestStr = requestBodyParam.toJSONString();
        System.out.println("requestStr=" + requestStr);

        String url = requestBodyParameters.getString("url");
        URI uri = new URI(url);
        // 明文加密方式
        String desJsonData = "";
        desJsonData = DesUtilTool.desEncrypt(requestStr);
        System.out.println("desJsonData: " + desJsonData);
        //post请求
        HttpClient httpClient = null;
        HttpPost postMethod = null;
        HttpResponse response = null;
        //获取http客户端
        httpClient = HttpClients.createDefault();
        postMethod = new HttpPost(uri);
        //设置请求头
        postMethod.addHeader("Content-Type", "application/json");
        postMethod.addHeader("Accept-Encoding", "application/json");
        postMethod.setHeader("Encoding", "application/json");
        postMethod.setEntity(new StringEntity(desJsonData, Charset.forName("UTF-8")));
        //传入请求参数
        response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("HTTP Status Code:" + statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("HTTP 请求未成功!HTTP Status Code:" + response.getStatusLine());
            return "HTTP 请求未成功!HTTP Status Code:" + response.getStatusLine();
        }
        HttpEntity httpEntity = response.getEntity();
        System.out.println("httpEntity:" + httpEntity);
        String responseContent = EntityUtils.toString(httpEntity, "UTF-8");
        //释放资源
        EntityUtils.consume(httpEntity);
        System.out.println("响应内容:" + responseContent);
        return responseContent;
    }

    @RequestMapping(value = "/webApiRequest", method = RequestMethod.POST)
    public String webAPIRequest(@RequestBody JSONObject requestBodyParameters) throws IOException, URISyntaxException {
        //参数处理 获取请求json串,并转换成string类型
        String requestBodyParam = requestBodyParameters.getString("request");
        requestBodyParam = requestBodyParam.substring(1, requestBodyParam.length() - 1);
        System.out.println("web api requestBodyParam=" + requestBodyParam);
        ArrayList arrayList = new ArrayList();
        System.out.println("requestBodyParam.split(\",\").length " + requestBodyParam.split(",").length);
        for (int i = 0; i < requestBodyParam.split(",").length; i++) {
            System.out.println("each param = " + requestBodyParam.split(",")[i].trim());
            arrayList.add(requestBodyParam.split(",")[i].trim());
        }
        String getParams = "";
        for (int j = 0; j < arrayList.size(); j++) {
            if (j == 0) {
                getParams = getParams + "?" + arrayList.get(j);
            } else {
                getParams = getParams + "&" + arrayList.get(j);
            }
        }
        System.out.println("getParams:" + getParams);
        String url = requestBodyParameters.getString("url");
        System.out.println("url=" + url);
        String finalUrl = url + getParams;
        System.out.println("finalUrl:" + finalUrl);
        URI uri = new URI(finalUrl);
        //get请求
        HttpClient httpClient = null;
        HttpGet getMethod = null;
        HttpResponse response = null;
        //获取http客户端
        httpClient = HttpClients.createDefault();
        getMethod = new HttpGet(uri);
        //设置请求头
        getMethod.addHeader("Content-Type", "application/json");
        getMethod.addHeader("Accept-Encoding", "application/json");
        response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("HTTP Status Code:" + statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("HTTP 请求未成功!HTTP Status Code:" + response.getStatusLine());
        }
        HttpEntity httpEntity = response.getEntity();
        System.out.println("httpEntity:" + httpEntity);
        String responseContent = EntityUtils.toString(httpEntity, "UTF-8");
        //释放资源
        EntityUtils.consume(httpEntity);
        System.out.println("响应内容:" + responseContent);
        return responseContent;
    }
 }

二、OkHttpClient简介

OkHttp是一个高效的HTTP客户端

特性:

  1. 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
  2. 连接池减少请求延时
  3. 透明的GZIP压缩减少响应数据的大小
  4. 缓存响应内容,避免一些完全重复的请求

使用步骤:

  1. 创建OkHttpClient对象
  2. 创建Request对象
  3. 将Request 对象封装为Call
  4. 通过Call 来执行同步或异步请求,调用execute方法同步执行,调用enqueue方法异步执行

使用实例:

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.util.Map;

@Slf4j
public class OkhttpUtil {

    public static String get(String url) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            log.error("get failed:", e);
        }
        return null;
    }

    public static String postChaosST(String url, Map params) {
        try {
            OkHttpClient client = new OkHttpClient();
            MultipartBody body = new MultipartBody.Builder()
                    .setType(MediaType.parse("multipart/form-data"))
                    .addFormDataPart("endpoint", params.get("endpoint"))
                    .addFormDataPart("cmd", params.get("cmd"))
                    .build();

            Request request = new Request.Builder()
                    .post(body)
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.code() == 200) {
                return response.body().string();
            }
            System.out.println();
        } catch (Exception e) {
            log.error("post failed:", e);
        }
        return null;
    }
}

你可能感兴趣的:(Java,http)