一.HttpClient、JsonPath、JsonObject运用
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.使用正则表达式匹配提取响应数据
- public class UserApiTest {
- private static CloseableHttpClient httpClient = null;
- @BeforeClass
- public static void setUp(){
- httpClient = HttpClients.createDefault(); //创建httpClient
- }
- @AfterClass
- public static void terDown() throws IOException{
- httpClient.close();
- }
- /*
- * 使用httpclient进行接口测试,所需jar包如下:
- *httpclient.jar、 httpcore.jar、 commons-logging.jar
- *get请求
- **/
- @Test
- public void userQueryWithRegTest1() throws ClientProtocolException, IOException{
- HttpGet request = new HttpGet("url地址"); // 创建请求
- //设置请求和连接超时时间,可以不设置
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout().setConnectTimeout().build();
- request.setConfig(requestConfig); //get请求设置请求和传输超时时间
- CloseableHttpResponse response = httpClient.execute(request); //执行请求
- String body = EntityUtils.toString(response.getEntity());
- response.close(); //释放连接
- System.out.println(body);
- //获取响应头信息
- Header headers[] = response.getAllHeaders();
- for(Header header:headers){
- System.out.println(header.getName()+": "+header.getValue());
- }
- // 打印响应信息
- System.out.println(response.getStatusLine().getStatusCode());
- }
- /*
- * 使用httpclient进行接口测试,所需jar包如下:
- *httpclient.jar、 httpcore.jar、 commons-logging.jar
- *get请求
- **/
- @Test
- public void testPost1() throws ClientProtocolException, IOException{
- HttpPost request = new HttpPost("http://101.200.167.51:8081/fund-api/expProduct");
- //设置post请求参数
- List<NameValuePair> foramParams = new ArrayList<NameValuePair>();
- foramParams.add(new BasicNameValuePair("name", "新手体验"));
- foramParams.add(new BasicNameValuePair("yieldRate", ""));
- foramParams.add(new BasicNameValuePair("extraYieldRate", ""));
- foramParams.add(new BasicNameValuePair("duration", ""));
- foramParams.add(new BasicNameValuePair("minBidAmount", ""));
- foramParams.add(new BasicNameValuePair("maxBidAmount", ""));
- UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(foramParams, "UTF-8");
- request.setEntity(urlEntity); //设置POST请求参数
- CloseableHttpResponse response = httpClient.execute(request); //执行post请求
- String body = EntityUtils.toString(response.getEntity());
- response.close(); //释放连接
- System.out.println(body);
- JSONObject jsonObj = JSONObject.fromObject(body);
- System.out.println("是否成功:"+jsonObj.getString("msg").equals("成功"));
- }
- /*
- * 用正则表达式提取响应数据
- * */
- @Test
- public void userQueryWithRegTest2() throws ClientProtocolException, IOException{
- HttpGet request = new HttpGet("url地址"); // 创建请求
- CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
- String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
- response.close();
- System.out.println(body);
- // "nickname":"([a-zA-Z0-9]*)"
- Pattern pattern = Pattern.compile("\"mobile\":\"(\\d+)\",\"nickname\":\"([a-zA-Z0-9]*)\".*\"status\":(\\d)"); // 从正则表达式得到一个模式对象
- Matcher matcher = pattern.matcher(body);// 对响应内容进行匹配
- while (matcher.find()) {
- String group0 = matcher.group(); // **_g0
- String group1 = matcher.group(); // **_g1
- String group2 = matcher.group(); // **_g1
- String group3 = matcher.group(); // **_g1
- System.out.println(group0 + "\t" + group1 + "\t" + group2 + "\t" + group3);
- }
- }
- /*
- * 使用JsonPath提取json响应数据中的数据
- * 需要的jar包:json-path-2.2.0.jar
- */
- @Test
- public void userQueryWithRegTest3() throws ClientProtocolException, IOException{
- HttpGet request = new HttpGet("url地址"); // 创建请求
- CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
- String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
- response.close();
- System.out.println(body);
- ReadContext ctx = JsonPath.parse(body);
- String mobile = ctx.read("$.data.mobile");
- String nickname = ctx.read("$.data.nickname");
- int status = ctx.read("$.data.status");
- String avatar = ctx.read("$.data.avatar");
- System.out.println(mobile + "\t" + nickname + "\t" + status + "\t" + avatar);
- }
- /*
- * 使用JSONObject插件处理响应数据
- * 所需的6个JAR包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-lang.jar
- */
- @Test
- public void userQueryWithRegTest5() throws ClientProtocolException, IOException{
- HttpGet request = new HttpGet("url地址"); // 创建请求
- CloseableHttpResponse response = httpClient.execute(request); // 执行某个请求
- String body = EntityUtils.toString(response.getEntity()); // 得到响应内容
- response.close();
- //将响应的字符串转换为JSONObject对象
- JSONObject jsonObj = JSONObject.fromObject(body);
- System.out.println(jsonObj.getString("code").equals(""));
- //data是对象中的一个对象,使用getJSONObject()获取
- JSONObject jsonObj1 = jsonObj.getJSONObject("data");
- System.out.println("status:"+jsonObj1.getInt("status")+"\n"+"nickname:"+jsonObj1.getString("nickname"));
- }
- /*
- * java代码转换json
- * 需要的jar包:json-lib
- * */
- @Test
- public void testJavaToJson(){
- System.out.println("--------------------------------------------------------------");
- System.out.println("java代码封装为json字符串:");
- JSONObject jsonObj = new JSONObject();
- jsonObj.put("username", "张三");
- jsonObj.put("password", "");
- System.out.println("java--->json: "+jsonObj.toString());
- System.out.println("--------------------------------------------------------------");
- }
- /*
- * json字符串转xml字符串
- * 需要的jar包:json-lib;xom
- * */
- @Test
- public void testJsonToXml(){
- System.out.println("--------------------------------------------------------------");
- System.out.println("json转xml字符串");
- String jsonStr = "{\"username\":\"张三\",\"password\":\"123456\"}";
- JSONObject jsonObj = JSONObject.fromObject(jsonStr);
- XMLSerializer xmlSerializer = new XMLSerializer();
- // 设置根元素名称
- xmlSerializer.setRootName("user_info");
- // 设置类型提示,即是否为元素添加类型 type = "string"
- xmlSerializer.setTypeHintsEnabled(false);
- String xml = xmlSerializer.write(jsonObj);
- System.out.println("json--->xml: "+xml);
- System.out.println("--------------------------------------------------------------");
- }
- /*
- * xml字符串转json字符串
- * 需要的jar包:json-lib;xom
- * */
- @Test
- public void testXmlToJson(){
- System.out.println("--------------------------------------------------------------");
- System.out.println("xml字符串转json字符串");
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
- XMLSerializer xmlSerializer = new XMLSerializer();
- JSON json= xmlSerializer.read(xml); //JSON是JSONObject的String形式
- System.out.println("xml---->json:"+json);
- System.out.println("--------------------------------------------------------------");
- }
- /*
- * javaBean转json
- * 需要的jar包:json-lib
- * */
- @Test
- public void testJavaBeanToJson(){
- System.out.println("--------------------------------------------------------------");
- System.out.println("javaBean转json");
- UserInfo userInfo = new UserInfo();
- userInfo.setUsername("张三");
- userInfo.setPassword("");
- JSONObject JsonObj = JSONObject.fromObject(userInfo);
- System.out.println("javaBean--->json:"+JsonObj.toString());
- System.out.println("--------------------------------------------------------------");
- }
- /*
- * javaBean转xml
- * 需要的jar包:json-lib;xom
- * */
- @Test
- public void testJavaBeanToXml(){
- System.out.println("--------------------------------------------------------------");
- System.out.println("javaBean转xml");
- UserInfo userInfo = new UserInfo();
- userInfo.setUsername("张三");
- userInfo.setPassword("");
- JSONObject JsonObj = JSONObject.fromObject(userInfo);
- XMLSerializer xmlSerializer = new XMLSerializer();
- xmlSerializer.setRootName("user_info");
- String xml = xmlSerializer.write(JsonObj, "UTF-8");
- System.out.println("javaBeanToXml--->xml:"+xml);
- System.out.println("--------------------------------------------------------------");
- }
- }
补充:
- /*
- *使用 java.net.URL.URL请求
- * */
- @Test
- public void useJavaUrl(){
- String httpUrl = "http://apis.baidu.com/showapi_open_bus/mobile/find";
- String httpArg = "num=13901452908";
- BufferedReader reader = null;
- String result = null;
- StringBuffer sbf = new StringBuffer();
- httpUrl = httpUrl + "?" + httpArg;
- try {
- URL url = new URL(httpUrl);
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
- connection.setRequestMethod("GET");
- // 填入apikey到HTTP header
- connection.setRequestProperty("apikey", "f584d68b4aebca91c154bffd397e05cd");
- connection.connect();
- InputStream is = connection.getInputStream();
- reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- String strRead = null;
- while ((strRead = reader.readLine()) != null) {
- sbf.append(strRead);
- sbf.append("\r\n");
- }
- reader.close();
- result = sbf.toString();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println(result);
- }
UserInfo:
- public class UserInfo {
- public String username;
- public String password;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
一.HttpClient、JsonPath、JsonObject运用的更多相关文章
- java http 请求的工具类
/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/pack ...
- 基于HttpClient JSONObject与JSONArray的使用
package com.spring.utils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.ap ...
- 基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport的接口自动化测试框架
接口自动化框架 项目说明 本框架是一套基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport而设计的数据驱动接口自动化测试框架,TestNG ...
- Java测试开发--JSONPath、JSONArray、JSONObject使用(十)
一.Maven项目,pom.xml文件中导入 <dependency> <groupId>com.alibaba</groupId> <artifactId& ...
- JsonPath入门教程
有时候需要从json里面提取相关数据,必须得用到如何提取信息的知识,下面来写一下 语法格式 JsonPath 描述 $ 根节点 @ 当前节点 .or[] 子节点 .. 选择所有符合条件的节点 * 所有 ...
- HttpClient相关
HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...
- httpClient实现微信公众号消息群发
1.实现功能 向关注了微信公众号的微信用户群发消息.(可以是所有的用户,也可以是提供了微信openid的微信用户集合) 2.基本步骤 前提: 已经有认证的公众号或者测试公众账号 发送消息步骤: 发送一 ...
- 使用httpclient 调用selenium webdriver
结合上次研究的selenium webdriver potocol ,自己写http request调用remote driver代替selenium API selenium web driver ...
- httpclient 使用方式介绍
第一:Get方式请求 package com.hct; import java.io.BufferedReader; import java.io.IOException; import java.i ...
随机推荐
- T-SQL 临时表、表变量、UNION
T-SQL 临时表.表变量.UNION 这次看一下临时表,表变量和Union命令方面是否可以被优化呢? 阅读导航 一.临时表和表变量 二.本次的另一个重头戏UNION 命令 一.临时表和表变量 很多数 ...
- bin文件和elf文件
ELF文件格式是一个开放标准,各种UNIX系统的可执行文件都采用ELF格式,它有三种不同的类型: 可重定位的目标文件(Relocatable,或者Object File) 可执行文件(Executab ...
- SVN插件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...
- 前两篇转载别人的精彩文章,自己也总结一下python split的用法吧!
前言:前两篇转载别人的精彩文章,自己也总结一下吧! 最近又开始用起py,是为什么呢? 自己要做一个文本相似度匹配程序,大致思路就是两个文档,一个是试题,一个是材料,我将试题按每题分割出来,再将每题的内 ...
- Flexible 弹性盒子模型之CSS flex-wrap 属性
实例 让弹性盒元素在必要的时候拆行: display:flex; flex-wrap: wrap; 复制 效果预览 浏览器支持 表格中的数字表示支持该属性的第一个浏览器的版本号. 紧跟在 -webki ...
- 驱动10.nor flash
1 比较nor/nand flash NOR NAND接口: RAM-Like,引脚多 引脚少, ...
- docker--------------实践(转载)
在私有云的容器化过程中,我们并不是白手起家开始的.而是接入了公司已经运行了多年的多个系统,包括自动编译打包,自动部署,日志监控,服务治理等等系统.在容器化之前,基础设施主要以物理机和虚拟机为主.因此, ...
- 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 解决方法是加一个软链: ...
- linux开启telnet服务
步骤: sudo apt-get install xinetd telnetd 安装成功后,系统会显示有相应得提示 sudo vim /etc/inetd.conf 并加入内容: teln ...
- 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 ...