美文网首页
Java开发小技巧:HttpClient工具类

Java开发小技巧:HttpClient工具类

作者: 哦00 | 来源:发表于2018-12-12 11:22 被阅读0次

    前言

    大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具有访问HTTP协议基本功能的高效工具类,为后续开发使用提供方便。

    文章要点:

    HttpClient使用流程

    工具类封装

    使用实例

    HttpClient使用流程

    1、导入Maven依赖

    org.apache.httpcomponentshttpclient4.5.5commons-codeccommons-codec1.11com.google.code.gsongson2.8.5

    2、创建HttpClient实例

    HttpClient client = HttpClientBuilder.create().build();

    3、创建请求方法的实例

    GET请求使用HttpGet,POST请求使用HttpPost,并传入请求的URL

    // POST请求HttpPost post =newHttpPost(url);// GET请求,URL中带请求参数HttpGet get =newHttpGet(url);

    4、添加请求参数

    普通形式

    List list =newArrayList<>();list.add(newBasicNameValuePair("username","admin"));list.add(newBasicNameValuePair("password","123456"));// GET请求方式// 由于GET请求的参数是拼装在URL后方,所以需要构建一个完整的URL,再创建HttpGet实例URIBuilder uriBuilder =newURIBuilder("http://www.baidu.com");uriBuilder.setParameters(list);HttpGet get =newHttpGet(uriBuilder.build());// POST请求方式post.setEntity(newUrlEncodedFormEntity(list, Charsets.UTF_8));

    JSON形式

    Map map =newHashMap<>();map.put("username","admin");map.put("password","123456");Gson gson =newGson();String json = gson.toJson(map,newTypeToken>() {}.getType());post.setEntity(newStringEntity(json, Charsets.UTF_8));post.addHeader("Content-Type","application/json");

    5、发送请求

    调用HttpClient实例的execute方法发送请求,返回一个HttpResponse对象

    HttpResponse response = client.execute(post);

    6、获取结果

    String result = EntityUtils.toString(response.getEntity());

    7、释放连接

    post.releaseConnection();

    工具类封装

    HttpClient工具类代码(根据相应使用场景进行封装):

    publicclassHttpClientUtil{// 发送GET请求publicstaticStringgetRequest(String path, List<NameValuePair> parametersBody)throwsRestApiException, URISyntaxException{        URIBuilder uriBuilder =newURIBuilder(path);        uriBuilder.setParameters(parametersBody);        HttpGet get =newHttpGet(uriBuilder.build());        HttpClient client = HttpClientBuilder.create().build();try{            HttpResponse response = client.execute(get);intcode = response.getStatusLine().getStatusCode();if(code >=400)thrownewRuntimeException((newStringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString());returnEntityUtils.toString(response.getEntity());        }catch(ClientProtocolException e) {thrownewRestApiException("postRequest -- Client protocol exception!", e);        }catch(IOException e) {thrownewRestApiException("postRequest -- IO error!", e);        }finally{            get.releaseConnection();        }    }// 发送POST请求(普通表单形式)publicstaticStringpostForm(String path, List<NameValuePair> parametersBody)throwsRestApiException{        HttpEntity entity =newUrlEncodedFormEntity(parametersBody, Charsets.UTF_8);returnpostRequest(path,"application/x-www-form-urlencoded", entity);    }// 发送POST请求(JSON形式)publicstaticStringpostJSON(String path, String json)throwsRestApiException{        StringEntity entity =newStringEntity(json, Charsets.UTF_8);returnpostRequest(path,"application/json", entity);    }// 发送POST请求publicstaticStringpostRequest(String path, String mediaType, HttpEntity entity)throwsRestApiException{        logger.debug("[postRequest] resourceUrl: {}", path);        HttpPost post =newHttpPost(path);        post.addHeader("Content-Type", mediaType);        post.addHeader("Accept","application/json");        post.setEntity(entity);try{            HttpClient client = HttpClientBuilder.create().build();            HttpResponse response = client.execute(post);intcode = response.getStatusLine().getStatusCode();if(code >=400)thrownewRestApiException(EntityUtils.toString(response.getEntity()));returnEntityUtils.toString(response.getEntity());        }catch(ClientProtocolException e) {thrownewRestApiException("postRequest -- Client protocol exception!", e);        }catch(IOException e) {thrownewRestApiException("postRequest -- IO error!", e);        }finally{            post.releaseConnection();        }    }}

    使用实例

    GET请求

    List parametersBody =newArrayList();parametersBody.add(newBasicNameValuePair("userId","admin"));String result = HttpClientUtil.getRequest("http://www.test.com/user",parametersBody);

    POST请求

    List parametersBody =newArrayList();parametersBody.add(newBasicNameValuePair("username","admin"));parametersBody.add(newBasicNameValuePair("password","123456"));String result = HttpClientUtil.postForm("http://www.test.com/login",parametersBody);

    POST请求(JSON形式)

    Map map =newHashMap<>();map.put("username","admin");map.put("password","123456");Gson gson =newGson();String json = gson.toJson(map,newTypeToken>() {}.getType());String result = HttpClientUtil.postJSON("http://www.test.com/login", json);                                                                                                欢迎工作一到五年的Java工程师朋友们加入Java群: 891219277

    群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!

    相关文章

      网友评论

          本文标题:Java开发小技巧:HttpClient工具类

          本文链接:https://www.haomeiwen.com/subject/vtyuhqtx.html