HttpClient详细应用请参考官方api文档:http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/index.html

1.使用httpclient进行接口测试,所需jar包如下:httpclient.jar、 httpcore.jar、 commons-logging.jar

2.使用JSONObject插件处理响应数据
 所需的6个JAR包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-lang.jar

3.使用正则表达式匹配提取响应数据

  1. public class UserApiTest {
  2. private static CloseableHttpClient httpClient = null;
  3.  
  4. @BeforeClass
  5. public static void setUp(){
  6. httpClient = HttpClients.createDefault(); //创建httpClient
  7. }
  8.  
  9. @AfterClass
  10. public static void terDown() throws IOException{
  11. httpClient.close();
  12. }
  13.  
  14. /*
  15. * 使用httpclient进行接口测试,所需jar包如下:
  16. *httpclient.jar、 httpcore.jar、 commons-logging.jar
  17. *get请求
  18. **/
  19. @Test
  20. public void userQueryWithRegTest1() throws ClientProtocolException, IOException{
  21. HttpGet request = new HttpGet("url地址"); // 创建请求
  22. //设置请求和连接超时时间,可以不设置
  23. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout().setConnectTimeout().build();
  24. request.setConfig(requestConfig); //get请求设置请求和传输超时时间
  25. CloseableHttpResponse response = httpClient.execute(request); //执行请求
  26. String body = EntityUtils.toString(response.getEntity());
  27. response.close(); //释放连接
  28. System.out.println(body);
  29.  
  30. //获取响应头信息
  31. Header headers[] = response.getAllHeaders();
  32. for(Header header:headers){
  33. System.out.println(header.getName()+": "+header.getValue());
  34. }
  35.  
  36. // 打印响应信息
  37. System.out.println(response.getStatusLine().getStatusCode());
  38. }
  39.  
  40. /*
  41. * 使用httpclient进行接口测试,所需jar包如下:
  42. *httpclient.jar、 httpcore.jar、 commons-logging.jar
  43. *get请求
  44. **/
  45. @Test
  46. public void testPost1() throws ClientProtocolException, IOException{
  47. HttpPost request = new HttpPost("http://101.200.167.51:8081/fund-api/expProduct");
  48. //设置post请求参数
  49. List<NameValuePair> foramParams = new ArrayList<NameValuePair>();
  50. foramParams.add(new BasicNameValuePair("name", "新手体验"));
  51. foramParams.add(new BasicNameValuePair("yieldRate", ""));
  52. foramParams.add(new BasicNameValuePair("extraYieldRate", ""));
  53. foramParams.add(new BasicNameValuePair("duration", ""));
  54. foramParams.add(new BasicNameValuePair("minBidAmount", ""));
  55. foramParams.add(new BasicNameValuePair("maxBidAmount", ""));
  56. UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(foramParams, "UTF-8");
  57. request.setEntity(urlEntity); //设置POST请求参数
  58. CloseableHttpResponse response = httpClient.execute(request); //执行post请求
  59. String body = EntityUtils.toString(response.getEntity());
  60. response.close(); //释放连接
  61. System.out.println(body);
  62. JSONObject jsonObj = JSONObject.fromObject(body);
  63. System.out.println("是否成功:"+jsonObj.getString("msg").equals("成功"));
  64. }
  65.  
  66. /*
  67. * 用正则表达式提取响应数据
  68. * */
  69. @Test
  70. public void userQueryWithRegTest2() throws ClientProtocolException, IOException{
  71. HttpGet request = new HttpGet("url地址"); // 创建请求
  72. CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
  73. String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
  74. response.close();
  75. System.out.println(body);
  76.  
  77. // "nickname":"([a-zA-Z0-9]*)"
  78. Pattern pattern = Pattern.compile("\"mobile\":\"(\\d+)\",\"nickname\":\"([a-zA-Z0-9]*)\".*\"status\":(\\d)"); // 从正则表达式得到一个模式对象
  79. Matcher matcher = pattern.matcher(body);// 对响应内容进行匹配
  80. while (matcher.find()) {
  81. String group0 = matcher.group(); // **_g0
  82. String group1 = matcher.group(); // **_g1
  83. String group2 = matcher.group(); // **_g1
  84. String group3 = matcher.group(); // **_g1
  85. System.out.println(group0 + "\t" + group1 + "\t" + group2 + "\t" + group3);
  86. }
  87.  
  88. }
  89.  
  90. /*
  91. * 使用JsonPath提取json响应数据中的数据
  92. * 需要的jar包:json-path-2.2.0.jar
  93. */
  94. @Test
  95. public void userQueryWithRegTest3() throws ClientProtocolException, IOException{
  96. HttpGet request = new HttpGet("url地址"); // 创建请求
  97. CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
  98. String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
  99. response.close();
  100. System.out.println(body);
  101.  
  102. ReadContext ctx = JsonPath.parse(body);
  103. String mobile = ctx.read("$.data.mobile");
  104. String nickname = ctx.read("$.data.nickname");
  105. int status = ctx.read("$.data.status");
  106. String avatar = ctx.read("$.data.avatar");
  107. System.out.println(mobile + "\t" + nickname + "\t" + status + "\t" + avatar);
  108. }
  109.  
  110. /*
  111. * 使用JSONObject插件处理响应数据
  112. * 所需的6个JAR包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-lang.jar
  113. */
  114. @Test
  115. public void userQueryWithRegTest5() throws ClientProtocolException, IOException{
  116. HttpGet request = new HttpGet("url地址"); // 创建请求
  117. CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
  118. String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
  119. response.close();
  120.  
  121. //将响应的字符串转换为JSONObject对象
  122. JSONObject jsonObj = JSONObject.fromObject(body);
  123. System.out.println(jsonObj.getString("code").equals(""));
  124. //data是对象中的一个对象,使用getJSONObject()获取
  125. JSONObject jsonObj1 = jsonObj.getJSONObject("data");
  126. System.out.println("status:"+jsonObj1.getInt("status")+"\n"+"nickname:"+jsonObj1.getString("nickname"));
  127. }
  128.  
  129. /*
  130. * java代码转换json
  131. * 需要的jar包:json-lib
  132. * */
  133. @Test
  134. public void testJavaToJson(){
  135. System.out.println("--------------------------------------------------------------");
  136. System.out.println("java代码封装为json字符串:");
  137. JSONObject jsonObj = new JSONObject();
  138. jsonObj.put("username", "张三");
  139. jsonObj.put("password", "");
  140. System.out.println("java--->json: "+jsonObj.toString());
  141. System.out.println("--------------------------------------------------------------");
  142. }
  143.  
  144. /*
  145. * json字符串转xml字符串
  146. * 需要的jar包:json-lib;xom
  147. * */
  148. @Test
  149. public void testJsonToXml(){
  150. System.out.println("--------------------------------------------------------------");
  151. System.out.println("json转xml字符串");
  152. String jsonStr = "{\"username\":\"张三\",\"password\":\"123456\"}";
  153. JSONObject jsonObj = JSONObject.fromObject(jsonStr);
  154. XMLSerializer xmlSerializer = new XMLSerializer();
  155. // 设置根元素名称
  156. xmlSerializer.setRootName("user_info");
  157. // 设置类型提示,即是否为元素添加类型 type = "string"
  158. xmlSerializer.setTypeHintsEnabled(false);
  159. String xml = xmlSerializer.write(jsonObj);
  160. System.out.println("json--->xml: "+xml);
  161. System.out.println("--------------------------------------------------------------");
  162. }
  163.  
  164. /*
  165. * xml字符串转json字符串
  166. * 需要的jar包:json-lib;xom
  167. * */
  168. @Test
  169. public void testXmlToJson(){
  170. System.out.println("--------------------------------------------------------------");
  171. System.out.println("xml字符串转json字符串");
  172. String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
  173. XMLSerializer xmlSerializer = new XMLSerializer();
  174. JSON json= xmlSerializer.read(xml); //JSON是JSONObject的String形式
  175. System.out.println("xml---->json:"+json);
  176. System.out.println("--------------------------------------------------------------");
  177. }
  178.  
  179. /*
  180. * javaBean转json
  181. * 需要的jar包:json-lib
  182. * */
  183. @Test
  184. public void testJavaBeanToJson(){
  185. System.out.println("--------------------------------------------------------------");
  186. System.out.println("javaBean转json");
  187. UserInfo userInfo = new UserInfo();
  188. userInfo.setUsername("张三");
  189. userInfo.setPassword("");
  190. JSONObject JsonObj = JSONObject.fromObject(userInfo);
  191. System.out.println("javaBean--->json:"+JsonObj.toString());
  192. System.out.println("--------------------------------------------------------------");
  193. }
  194.  
  195. /*
  196. * javaBean转xml
  197. * 需要的jar包:json-lib;xom
  198. * */
  199. @Test
  200. public void testJavaBeanToXml(){
  201. System.out.println("--------------------------------------------------------------");
  202. System.out.println("javaBean转xml");
  203. UserInfo userInfo = new UserInfo();
  204. userInfo.setUsername("张三");
  205. userInfo.setPassword("");
  206. JSONObject JsonObj = JSONObject.fromObject(userInfo);
  207. XMLSerializer xmlSerializer = new XMLSerializer();
  208. xmlSerializer.setRootName("user_info");
  209. String xml = xmlSerializer.write(JsonObj, "UTF-8");
  210. System.out.println("javaBeanToXml--->xml:"+xml);
  211. System.out.println("--------------------------------------------------------------");
  212. }
  213. }

补充:

  1.    /*
  2. *使用 java.net.URL.URL请求
  3. * */
  4. @Test
  5. public void useJavaUrl(){
  6. String httpUrl = "http://apis.baidu.com/showapi_open_bus/mobile/find";
  7. String httpArg = "num=13901452908";
  8. BufferedReader reader = null;
  9. String result = null;
  10. StringBuffer sbf = new StringBuffer();
  11. httpUrl = httpUrl + "?" + httpArg;
  12.  
  13. try {
  14. URL url = new URL(httpUrl);
  15. HttpURLConnection connection = (HttpURLConnection) url
  16. .openConnection();
  17. connection.setRequestMethod("GET");
  18. // 填入apikey到HTTP header
  19. connection.setRequestProperty("apikey", "f584d68b4aebca91c154bffd397e05cd");
  20. connection.connect();
  21. InputStream is = connection.getInputStream();
  22. reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  23. String strRead = null;
  24. while ((strRead = reader.readLine()) != null) {
  25. sbf.append(strRead);
  26. sbf.append("\r\n");
  27. }
  28. reader.close();
  29. result = sbf.toString();
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. System.out.println(result);
  34. }

UserInfo:

  1. public class UserInfo {
  2. public String username;
  3. public String password;
  4. public String getUsername() {
  5. return username;
  6. }
  7. public void setUsername(String username) {
  8. this.username = username;
  9. }
  10. public String getPassword() {
  11. return password;
  12. }
  13. public void setPassword(String password) {
  14. this.password = password;
  15. }
  16.  
  17. }

一.HttpClient、JsonPath、JsonObject运用的更多相关文章

  1. java http 请求的工具类

    /*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/pack ...

  2. 基于HttpClient JSONObject与JSONArray的使用

    package com.spring.utils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.ap ...

  3. 基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport的接口自动化测试框架

    接口自动化框架 项目说明 本框架是一套基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport而设计的数据驱动接口自动化测试框架,TestNG ...

  4. Java测试开发--JSONPath、JSONArray、JSONObject使用(十)

    一.Maven项目,pom.xml文件中导入 <dependency> <groupId>com.alibaba</groupId> <artifactId& ...

  5. JsonPath入门教程

    有时候需要从json里面提取相关数据,必须得用到如何提取信息的知识,下面来写一下 语法格式 JsonPath 描述 $ 根节点 @ 当前节点 .or[] 子节点 .. 选择所有符合条件的节点 * 所有 ...

  6. HttpClient相关

    HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...

  7. httpClient实现微信公众号消息群发

    1.实现功能 向关注了微信公众号的微信用户群发消息.(可以是所有的用户,也可以是提供了微信openid的微信用户集合) 2.基本步骤 前提: 已经有认证的公众号或者测试公众账号 发送消息步骤: 发送一 ...

  8. 使用httpclient 调用selenium webdriver

    结合上次研究的selenium webdriver potocol ,自己写http request调用remote driver代替selenium API selenium web driver ...

  9. httpclient 使用方式介绍

    第一:Get方式请求 package com.hct; import java.io.BufferedReader; import java.io.IOException; import java.i ...

随机推荐

  1. T-SQL 临时表、表变量、UNION

    T-SQL 临时表.表变量.UNION 这次看一下临时表,表变量和Union命令方面是否可以被优化呢? 阅读导航 一.临时表和表变量 二.本次的另一个重头戏UNION 命令 一.临时表和表变量 很多数 ...

  2. bin文件和elf文件

    ELF文件格式是一个开放标准,各种UNIX系统的可执行文件都采用ELF格式,它有三种不同的类型: 可重定位的目标文件(Relocatable,或者Object File) 可执行文件(Executab ...

  3. SVN插件

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  4. 前两篇转载别人的精彩文章,自己也总结一下python split的用法吧!

    前言:前两篇转载别人的精彩文章,自己也总结一下吧! 最近又开始用起py,是为什么呢? 自己要做一个文本相似度匹配程序,大致思路就是两个文档,一个是试题,一个是材料,我将试题按每题分割出来,再将每题的内 ...

  5. Flexible 弹性盒子模型之CSS flex-wrap 属性

    实例 让弹性盒元素在必要的时候拆行: display:flex; flex-wrap: wrap; 复制 效果预览 浏览器支持 表格中的数字表示支持该属性的第一个浏览器的版本号. 紧跟在 -webki ...

  6. 驱动10.nor flash

    1 比较nor/nand flash NOR                                  NAND接口:    RAM-Like,引脚多                 引脚少, ...

  7. docker--------------实践(转载)

    在私有云的容器化过程中,我们并不是白手起家开始的.而是接入了公司已经运行了多年的多个系统,包括自动编译打包,自动部署,日志监控,服务治理等等系统.在容器化之前,基础设施主要以物理机和虚拟机为主.因此, ...

  8. Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)的解决方法

    在连接数据库时,报这个错误,是/var/lib/mysql/ 目录下没有mysql.sock文件,在服务器搜索myslq.sock文件,我的是在/tmp/mysql.sock 解决方法是加一个软链: ...

  9. linux开启telnet服务

    步骤: sudo apt-get install xinetd telnetd     安装成功后,系统会显示有相应得提示 sudo vim /etc/inetd.conf  并加入内容:  teln ...

  10. Help improve Android Studio by sending usage statistics to Google

    Please press I agree if you want to help make Android Studio better or I don't agree otherwise. more ...