一,基础的的应用

1.1,get的无参请求

     @Test
     public void doGet() throws Exception {
         //创建一个httpclient对象
         CloseableHttpClient httpClient = HttpClients.createDefault();
         //创建一个GET对象
         HttpGet get = new HttpGet("http://www.sogou.com");
         //执行请求
         CloseableHttpResponse response = httpClient.execute(get);
         //取响应的结果
         int statusCode = response.getStatusLine().getStatusCode();
         System.out.println(statusCode);
         HttpEntity entity = response.getEntity();
         String string = EntityUtils.toString(entity, "utf-8");
         System.out.println(string);
         //关闭httpclient
         response.close();
         httpClient.close();
     }

1.2,get的带参请求

 public void doGetWithParam() throws Exception{
         //创建一个httpclient对象
         CloseableHttpClient httpClient = HttpClients.createDefault();
         //创建一个uri对象
         URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
         uriBuilder.addParameter("query", "花千骨");
         HttpGet get = new HttpGet(uriBuilder.build());
         //执行请求
         CloseableHttpResponse response = httpClient.execute(get);
         //取响应的结果
         int statusCode = response.getStatusLine().getStatusCode();
         System.out.println(statusCode);
         HttpEntity entity = response.getEntity();
         String string = EntityUtils.toString(entity, "utf-8");
         System.out.println(string);
         //关闭httpclient
         response.close();
         httpClient.close();
     }

1.3,post的无参请求

 public void doPost() throws Exception {
         CloseableHttpClient httpClient = HttpClients.createDefault();

         //创建一个post对象
         HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
         //执行post请求
         CloseableHttpResponse response = httpClient.execute(post);
         String string = EntityUtils.toString(response.getEntity());
         System.out.println(string);
         response.close();
         httpClient.close();

     }

1.4.1,post的带参请求

 public void doPostWithParam() throws Exception{
         CloseableHttpClient httpClient = HttpClients.createDefault();

         //创建一个post对象
         HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
         //创建一个Entity。模拟一个表单
         List<NameValuePair> kvList = new ArrayList<>();
         kvList.add(new BasicNameValuePair("username", "张三"));
         kvList.add(new BasicNameValuePair("password", "123"));

         //包装成一个Entity对象
         StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
         //设置请求的内容
         post.setEntity(entity);

         //执行post请求
         CloseableHttpResponse response = httpClient.execute(post);
         String string = EntityUtils.toString(response.getEntity());
         System.out.println(string);
         response.close();
         httpClient.close();
     }

1.4.2,post的请求服务器8082的写法

 @RequestMapping(value="/httpclient/post", method=RequestMethod.POST,
             produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
     @ResponseBody
     public String testPost(String username, String password) {
         String result = "username:" + username + "\tpassword:" + password;
         System.out.println(result);
         return "username:" + username + ",password:" + password;
     }

二,httpclient的工具封装

2.1,get的带参和无参的工具类

     public static String doGet(String url, Map<String, String> param) {

         // 创建Httpclient对象
         CloseableHttpClient httpclient = HttpClients.createDefault();

         String resultString = "";
         CloseableHttpResponse response = null;
         try {
             // 创建uri
             URIBuilder builder = new URIBuilder(url);
             if (param != null) {
                 for (String key : param.keySet()) {
                     builder.addParameter(key, param.get(key));
                 }
             }
             URI uri = builder.build();

             // 创建http GET请求
             HttpGet httpGet = new HttpGet(uri);

             // 执行请求
             response = httpclient.execute(httpGet);
             // 判断返回状态是否为200
             if (response.getStatusLine().getStatusCode() == 200) {
                 resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
             }
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 if (response != null) {
                     response.close();
                 }
                 httpclient.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return resultString;
     }

     public static String doGet(String url) {
         return doGet(url, null);
     }

2.2,post的带参和无参的工具类 (参数的数据类型是map)

 public static String doPost(String url, Map<String, String> param) {
         // 创建Httpclient对象
         CloseableHttpClient httpClient = HttpClients.createDefault();
         CloseableHttpResponse response = null;
         String resultString = "";
         try {
             // 创建Http Post请求
             HttpPost httpPost = new HttpPost(url);
             // 创建参数列表
             if (param != null) {
                 List<NameValuePair> paramList = new ArrayList<>();
                 for (String key : param.keySet()) {
                     paramList.add(new BasicNameValuePair(key, param.get(key)));
                 }
                 // 模拟表单
                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                 httpPost.setEntity(entity);
             }
             // 执行http请求
             response = httpClient.execute(httpPost);
             resultString = EntityUtils.toString(response.getEntity(), "utf-8");
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 response.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }

         return resultString;
     }

     public static String doPost(String url) {
         return doPost(url, null);
     }
     

2.3,post的带参的请求(参数类型是json格式的数据)

 public static String doPostJson(String url, String json) {
         // 创建Httpclient对象
         CloseableHttpClient httpClient = HttpClients.createDefault();
         CloseableHttpResponse response = null;
         String resultString = "";
         try {
             // 创建Http Post请求
             HttpPost httpPost = new HttpPost(url);
             // 创建请求内容
             StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
             httpPost.setEntity(entity);
             // 执行http请求
             response = httpClient.execute(httpPost);
             resultString = EntityUtils.toString(response.getEntity(), "utf-8");
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 response.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }

         return resultString;
     }

三,项目中的案例解析 (调用其它公司的图像识别为例)

3.1,调用的服务层的方法(第一个参数不一样,说明识别的证件不一样)

     private OcrServer ocrServer = null;

     @Override
     public Map<String, Object> idCardRecognize(MultipartFile imageFile) {
         return ocrServer.pictureRecognition("IdCard", imageFile);
     }

     @Override
     public Map<String, Object> bankCardRecognize(MultipartFile imageFile) {
         return ocrServer.pictureRecognition("BankCard", imageFile);
     }

     @Override
     public Map<String, Object> veCardRecognize(MultipartFile imageFile) {
         return ocrServer.pictureRecognition("VeCard", imageFile);
     }

     @Override
     public Map<String, Object> driverCardRecognize(MultipartFile imageFile) {
         return ocrServer.pictureRecognition("DriverCard", imageFile);
     }

     @Override
     public Map<String, Object> businessLicenseRecognize(MultipartFile imageFile) {
         return ocrServer.pictureRecognition("BusinessLicense", imageFile);
     }

     @Override
     public Map<String, Object> ocrRecognize(String recotype,
             MultipartFile imageFile) {
         return ocrServer.pictureRecognition(recotype, imageFile);
     }

     public void setOcrServer(OcrServer ocrServer) {
         this.ocrServer = ocrServer;
     }

3.2,参数的封装,url的确定

 public Map<String, Object> pictureRecognition(String recotype, MultipartFile imageFile) {
         long begin = System.currentTimeMillis();
         String result = null;
         // 文件输入流
         FileInputStream fs = null;
         try {
             String configValue = cpConfigService.getValueByConfigKey("ocr_server_config", "{'uri':'http://cloud.exocr.com/recognize','username':'test','password':'test'}");
             Map<String, String> configMap = JsonUtils.json2Map2(configValue);
             String postUrl = configMap.get("uri"); // 服务地址
             Map<String, String> postParam = new HashMap<String, String>(10);
             postParam.put("username", configMap.get("username")); // 用户名, 公有云测试可使用’test’
             postParam.put("password", configMap.get("password")); // 密码,公有云测试可使用 ’test’
             postParam.put("recotype", recotype); // BankCard
             postParam.put("encoding", "utf-8"); // 返回结果的文字编码方式,取值包括:utf-8, 默认值 gb2312
             postParam.put("head_portrait", "0"); // 是否返回头像(base64格式),只对身份证识别有效,取值范围:0,默认,不返回头像    1,则返回身份证的头像照片
             postParam.put("crop_image", "0"); // 是否返回切边(base64格式),取值:0,    默认,不返回切边图    1,    返回切边图
             postParam.put("b64", "1"); // 输入图片是否为base64格式,取值:0,    默认,二进制格式   1,    base64格式
             // base64编码图像
             String base64 = new String(Base64.encodeBase64(imageFile.getBytes()));
             postParam.put("image", base64); // 待识别的图像,可以是二进制也可以是base64格式
             result = HttpUtil.postUrlAsString(postUrl, postParam, null, "utf-8");
             logger.info("OCR识别结果{}", result);
         } catch (Exception e) {
             logger.error("OCR识别异常:", e);
             StringBuilder sb = new StringBuilder();
             sb.append("{'Error':'99','Details':'OCR识别异常:");
             sb.append(e.getMessage()).append("'}");
             result = sb.toString();
         } finally {
             if (null != fs) {
                 try {
                     fs.close();
                 } catch (IOException e) {
                     logger.error("File input stream close exception:", e);
                 }
             }
         }
         // 记录接口调用耗时
         logger.info("OCR服务调用耗时{},识别类型{}", System.currentTimeMillis() - begin, recotype);

         try {
             return JsonUtils.json2Map(result);
         } catch (Exception e) {
             logger.error("json to map exception:", e);
         }

         return null;
     }

 在这里假如没有特殊的请求的话完全可以 result = HttpUtil.postUrlAsString(postUrl, postParam, null, "utf-8")调用工具类的方法了返回的结果就是了。

     public static String postUrlAsString(String url,
             Map<String, String> params, Map<String, String> reqHeader,
             String encode) throws Exception {
         // 开始时间
         long t1 = System.currentTimeMillis();
         // 获得HttpPost对象
         HttpPost httpPost = getHttpPost(url, params, encode);
         // 发送请求
         String result = executeHttpRequest(httpPost, reqHeader, encode);
         // 结束时间
         long t2 = System.currentTimeMillis();
         // 调试信息
         logger.debug("url:" + url);
         logger.debug("params:" + params.toString());
         logger.debug("reqHeader:" + reqHeader);
         logger.debug("encode:" + encode);
         logger.debug("result:" + result);
         logger.debug("consume time:" + ((t2 - t1)));
         // 返回结果
         return result;
     } 

3.3,httppost对象的获取

   private static HttpPost getHttpPost(String url, Map<String, String> params,
             String encode) throws UnsupportedEncodingException {
         HttpPost httpPost = new HttpPost(url);
         if (params != null) {
             List<NameValuePair> form = new ArrayList<NameValuePair>();
             for (String name : params.keySet()) {
                 form.add(new BasicNameValuePair(name, params.get(name)));
             }

             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
                     encode);
             httpPost.setEntity(entity);
         }

         return httpPost;
     }  

3.4,把获取到的参数传递给httppost对象

 private static String executeHttpRequest(HttpUriRequest request,
             Map<String, String> reqHeader, String encode) throws Exception {
         HttpClient client = null;
         String result = null;
         try {
             // 创建HttpClient对象
             client = new DefaultHttpClient();
             // 设置连接超时时间
             client.getParams().setParameter(
                     CoreConnectionPNames.CONNECTION_TIMEOUT, 60);
             // 设置Socket超时时间
             client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                     36600);
             // 设置请求头信息
             if (reqHeader != null) {
                 for (String name : reqHeader.keySet()) {
                     request.addHeader(name, reqHeader.get(name));
                 }
             }
             // 获得返回结果
             HttpResponse response = client.execute(request);
             // 如果成功
             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                 encode = StringUtils.isNotEmpty(encode) ? encode : DEFAULT_ENCODE;
                 result = EntityUtils.toString(response.getEntity(), encode);
             } else {
                 StringBuffer errorMsg = new StringBuffer();
                 errorMsg.append("httpStatus:");
                 errorMsg.append(response.getStatusLine().getStatusCode());
                 errorMsg.append(response.getStatusLine().getReasonPhrase());
                 errorMsg.append(", Header: ");
                 Header[] headers = response.getAllHeaders();
                 for (Header header : headers) {
                     errorMsg.append(header.getName());
                     errorMsg.append(":");
                     errorMsg.append(header.getValue());
                 }
                 logger.error("HttpResonse Error:" + errorMsg);
                 result = "{'Error':'98','Details':'" + errorMsg.toString() + "'}";
             }
         } catch (Exception e) {
             logger.error("http连接异常", e);
             throw new Exception("http连接异常");
         } finally {
             try {
                 client.getConnectionManager().shutdown();
             } catch (Exception e) {
                 logger.error("finally HttpClient shutdown error", e);
             }
         }
         return result;
     }  

四,总结

其实httpclient主要就是模仿浏览器来通过java代码调用另一个服务器或者应用的,其中最主要的就是url和参数,一般情况下都会用post带参的请求,有些情况下也有可能有抬头或者时间的这些额外的设置。

httpclient的get带参不带参post带参不带参的简单应用的更多相关文章

  1. UNITY自带的PACKAGE的UTILITY 里面有一个自带的FPS COUNTER

    UNITY自带的PACKAGE的UTILITY 里面有一个自带的FPS COUNTER 可用,但是脚本是保密的?

  2. php通过JavaBridge调用Java类库和不带包的自定义java类成功 但是调用带包的自定义Java类报错,该怎么解决

    php通过JavaBridge调用Java类库和不带包的自定义java类成功 但是调用带包的自定义Java类报错,Class.forName("com.mysql.jdbc.Driver&q ...

  3. vue-router 使用query传参跳转了两次(首次带参数,跳转到了不带参数)

    问题: 在做项目的过程中,使用query传参数,发现跳转过程中第一次有参数,但是路由马上又跳转了一次,然后 ?和它之后的参数都不见了 问题分析: 因为路由加载了两次 解决办法: ·1. 找到总的 la ...

  4. 学习懈怠的时候,可以运行Qt自带的Demo,或者Delphi控件自带的Demo,或者Cantu书带的源码,运行一下Boost的例子(搞C++不学习Boost/Poco/Folly绝对是一大损失,有需要使用库要第一时间想到)(在六大的痛苦经历说明,我的理论性确实不强,更适合做实践)

    这样学还不用动脑子,而且熟悉控件也需要时间,而且慢慢就找到感觉了,就可以精神抖擞的恢复斗志干活了.或者Cantu书带的源码. 并且可以使用Mac SSD运行Qt的Demo,这样运行速度快一点. 此外, ...

  5. Asp.net Core dotnet 发布类库文件 带上注释,发布预发行版,带上所有引用

    带上注释 效果图 带上所有引用 效果图 预发行版 效果图 由于微软取消了  project.json  这个json 转而用了csproj 用于保存配置 所以懵逼很大一会 资料来源 project.j ...

  6. Flutter路由跳转父级页面向子页面传参及子页面向父级页面传参

    Flutter中页面通过路由跳转传参主要分两种,一种是通过push()跳转时根据设定的参数进行传参,另一种是通过pop()返回时进行传参. 父级页面向子页面push()传参 假设从A页面跳到B页面可能 ...

  7. 用mac自带的safari浏览器下载excel文件后面自带了.exe后缀

    将 Content-Type 设为 application/vnd.ms-excel

  8. 老猪带你玩转自定义控件三——sai大神带我实现ios 8 时间滚轮控件

    ios 8 的时间滚轮控件实现了扁平化,带来很好用户体验,android没有现成控件,小弟不才,数学与算法知识不过关,顾十分苦恼,幸好在github上找到sai大神实现代码,甚为欣喜,顾把学习这个控件 ...

  9. python带你采集不可言说网站数据,并带你多重骚操作~

    前言 嗨喽,大佬们好鸭!这里是小熊猫~ 今天我们采集国内知名的shipin弹幕网站! 这里有及时的动漫新番,活跃的ACG氛围,有创意的Up主. 大家可以在这里找到许多欢乐. 目录(可根据个人情况点击你 ...

  10. python 带参与不带参装饰器的使用与流程分析/什么是装饰器/装饰器使用注意事项

    一.什么是装饰器 装饰器是用来给函数动态的添加功能的一种技术,属于一种语法糖.通俗一点讲就是:在不会影响原有函数的功能基础上,在原有函数的执行过程中额外的添加上另外一段处理逻辑 二.装饰器功能实现的技 ...

随机推荐

  1. BZOJ 1998: [Hnoi2010]Fsk物品调度 [置换群 并查集]

    传送门 流水线上有n个位置,从0到n-1依次编号,一开始0号位置空,其它的位置i上有编号为i的盒子.Lostmonkey要按照以下规则重新排列这些盒子. 规则由5个数描述,q,p,m,d,s,s表示空 ...

  2. 自动化测试selenium(四)check,选中复选框,操作一组元素

    定位复选框位置 打开浏览器,按F12,审查元素 接下来,我们要实现选中复选框 List<WebElement> inputs = driver.findElements(By.tagNam ...

  3. Bootstrap+Vue.js 练习入门一

    一. 效果如下图所示,输入用户名和年龄,点击添加,数据会自动添加到下面的用户信息表内.当没有数据时,用户信息表显示:暂无数据……,当有数据时,显示 删除全部 按钮,这里为了方便快捷,我没有做删除按钮的 ...

  4. 安装RabbitMQ(一)

    RabbitMQ简介 RabbitMQ 是由 LShift 提供的一个 Advanced Message Queuing Protocol (AMQP) 的开源实现,由以高性能.健壮以及可伸缩性出名的 ...

  5. 从Myeclipse到Intelj Idea

    前言:经历了从eclipse到Myeclipse的时间,大学时候用Eclipse,开始工作的时候选择Myeclipse,都能体会到Java的IDE的先进和高明之处,直到最近,公司项目采git和Grad ...

  6. centos7安装部署gitlab服务器

    [gitlab需要内存至少4GB]   我这里使用的是centos 7 64bit,我试过centos 6也是可以的! 1. 安装依赖软件 yum -y install policycoreutils ...

  7. JS实现图片''推拉门''效果

    JS实现图片''推拉门''效果   ''推拉门''动效也可以称作"手风琴"效果,大多数效果实现的思路基本是一样的,下面介绍两种方法,一种是通过改变图片的偏移位置实现移动,另一种是通 ...

  8. pinvoke 数据交互笔记

    intptr to array string string[]  _outputStrArray=null;  int channelCount = 0;///返回数组大小            In ...

  9. prop&attr区别和用法,以多选框为例

    1.比较 相同点 : prop和attr作为jquery的方法都可以获取属性值; 不同点 : (1) 对于HTML元素本身就带有的固有属性,使用prop方法, attr获取checkbox的check ...

  10. 解决maven项目Cannot change version of project facet Dynamic web module to 3.0

    问题描述         用Eclipse创建Maven结构的web项目的时候选择了Artifact Id为maven-artchetype-webapp,由于这个catalog比较老,用的servl ...