【接口】HttpClient 处理get和post请求(二)(2019-07-14 18:41)
一、环境准备
1.导入httpClient依赖包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
导入fastJson依赖实现实体类序列化和json反序列操作
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
testng依赖
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
二、Get请求发包代码实现
package test; import java.util.Arrays;
import java.util.HashMap; import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.Test; import com.alibaba.fastjson.JSONObject; public class HttpClientTest {
String url = "http://localhost:8081/user/login";
String get_params = "username=xiaobing&password=123456";
@Test
public void GetTest() {
//创建HttpGet对象
HttpGet httpGet = new HttpGet(url+"?"+get_params);
//准备HttpClient客户端
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
//发送请求
httpResponse = httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
//取出响应状态码
int code = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:"+code);
//取出消息头
Header[] header = httpResponse.getAllHeaders();
System.out.println("消息头:"+Arrays.toString(header));
//取出响应报文
String result = null;
try {
//使用EntityUtils工具类将Entity实体类toString转换
result = EntityUtils.toString(httpResponse.getEntity());
System.out.println("响应报文:"+result);
} catch (Exception e) {
e.printStackTrace();
}
HashMap<String, String> map = JSONObject.parseObject(result, HashMap.class);
String actual = map.get("message");
System.out.println("actual_message:"+actual);
String expected = "登录成功";
//断言
Assert.assertEquals(actual, expected);
}
}
响应码:200
消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 14:06:44 GMT]
响应报文:{"status":"1","message":"登录成功"}
actual_message:登录成功
PASSED: GetTest
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
三、POST请求发包代码实现(表单方式)
服务端:
@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.POST,consumes="application/x-www-form-urlencoded")
public Result login(User user) {
。。。 。。。
}
客户端:
@Test
public void postFormSend() {
//测试数据准备
String url = "http://localhost:8081/user/login";
String params = "username=xiaobing&password=123456";
//创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
//将Content-Type类型添加到消息头
Header header = new BasicHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
httpPost.addHeader(header);
//将表单参数添加到Entity实体类放到请求体
HttpEntity entity = new StringEntity(params, "UTF-8");
httpPost.setEntity(entity);
//准备HttpClient客户端
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
//发起请求
httpResponse =httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
int code = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:"+code);
Header[] resHeader = httpResponse.getAllHeaders();
System.out.println("消息头:"+Arrays.toString(resHeader));
HttpEntity httpEntity = httpResponse.getEntity();
String result = null;
try {
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("响应报文:"+result);
HashMap<String, String> map = JSONObject.parseObject(result, HashMap.class);
String actual = map.get("message");
System.out.println("actual_message:"+actual);
String expected = "登录成功";
//断言
Assert.assertEquals(actual, expected); }
响应码:200
消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 15:13:53 GMT]
响应报文:{"status":"1","message":"登录成功"}
actual_message:登录成功
PASSED: postFormSend
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
四、POST请求发包代码实现(Json方式)
服务端:
@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.POST,consumes="application/json")
public Result login(@RequestBody(required=false)User user) {
。。。 。。。
}
客户端:
@Test
public void postJsonSend() {
//测试数据准备
String url = "http://localhost:8081/user/login";
String params = "{\"username\":\"xiaobing\",\"password\":\"123456\"}";
//创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
//将Content-Type类型添加到消息头
Header header = new BasicHeader("Content-Type","application/json;charset=utf-8");
httpPost.addHeader(header);
//将表单参数添加到Entity实体类放到请求体
HttpEntity entity = new StringEntity(params, "UTF-8");
httpPost.setEntity(entity);
//准备HttpClient客户端
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
//发起请求
httpResponse =httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
int code = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:"+code);
Header[] resHeader = httpResponse.getAllHeaders();
System.out.println("消息头:"+Arrays.toString(resHeader));
HttpEntity httpEntity = httpResponse.getEntity();
String result = null;
try {
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("响应报文:"+result);
HashMap<String, String> map = JSONObject.parseObject(result, HashMap.class);
String actual = map.get("message");
System.out.println("actual_message:"+actual);
String expected = "登录成功";
//断言
Assert.assertEquals(actual, expected); }
响应码:200
消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 15:18:53 GMT]
响应报文:{"status":"1","message":"登录成功"}
actual_message:登录成功
PASSED: postJsonSend
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
五、代码整合
未完待续。。。
【接口】HttpClient 处理get和post请求(二)(2019-07-14 18:41)的更多相关文章
- Java学习心得之 HttpClient的GET和POST请求
作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Java学习心得之 HttpClient的GET和POST请求 1. 前言2. GET请求3 ...
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
讲这个之前,我们先来说说get和post两种请求的区别吧!!! 1. GET提交的数据会放在URL之后,以?分割URL和传输数据,参数之间以&相连,如EditPosts.jsp?name=te ...
- C# ASP.NET Core使用HttpClient的同步和异步请求
引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...
- Android笔记---使用HttpClient发送POST和GET请求
在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...
- (办公)访问其他系统接口httpClient,异步访问
访问其他系统接口httpClient,但是都是同步的,同步意味当前线程是阻塞的,只有本次请求完成后才能进行下一次请求;异步意味着所有的请求可以同时塞入缓冲区,不阻塞当前的线程; httpClient请 ...
- 使用HttpClient来异步发送POST请求并解析GZIP回应
.NET 4.5(C#): 使用HttpClient来异步发送POST请求并解析GZIP回应 在新的C# 5.0和.NET 4.5环境下,微软为C#加入了async/await,同时还加入新的Syst ...
- java 封装httpclient 的get 和post 请求
import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util. ...
- Java实现HttpClient发送GET、POST请求(https、http)
1.引入相关依赖包 jar包下载:httpcore4.5.5.jar fastjson-1.2.47.jar maven: <dependency> <groupId>o ...
- HTTPClient模拟Get和Post请求
一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...
随机推荐
- Linux系类(8) - 文件搜索命令locate
文件搜索命令locate 命令格式 locate [文件名] 在后台数据库中按文件名搜索,搜索速度更快,而find.which是遍历所有目录去查找:后台数据库在/var/lib/mlocate (保存 ...
- ELK实战部署
环境 : 一台 centos 6.7 IP地址: 192.168.88.250 软件版本 : ElasticSearch 2.1.0 Logstash 2.1.1 Kibana 4.3.1 ...
- Jmeter导出测试报告
测试数据概述 jemter导出数据 另存为导出csv文件 命令行导出 测试报告的作用: 反馈结果 复现问题,所以需要写明测试场景.数据
- 关于selenium中的三种等待方式与EC模块的知识
1. 强制等待 第一种也是最简单粗暴的一种办法就是强制等待sleep(xx),强制让闪电侠等xx时间,不管凹凸曼能不能跟上速度,还是已经提前到了,都必须等xx时间. 看代码: 1 2 3 4 5 6 ...
- re.findall用法
其中,re.findall() 函数可以遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表. 在python源代码中,展示如下: 搜索string,返回一个顺序访问每一个匹配结果(Match对象 ...
- CF280C-Game on Tree【数学期望】
正题 题目链接:https://www.luogu.com.cn/problem/CF280C 题目大意 \(n\)个点的一棵树,每次选择一个没有染色的点把它和它的子树染黑,求期望全部染黑的步数. 解 ...
- 三、mybatis多表关联查询和分布查询
前言 mybatis多表关联查询和懒查询,这篇文章通过一对一和一对多的实例来展示多表查询.不过需要掌握数据输出的这方面的知识.之前整理过了mybatis入门案例和mybatis数据输出,多表查询是在前 ...
- 模拟一个简单的tomcat
目录 简单处理 每个请求一个线程 模拟tomcat 参考 简单处理 // 客户端和服务器的通信,说到底就是两个数据的传输, // 客户端发送inputStream给服务器,服务器回复 // outpu ...
- 每个男孩的机械梦「GitHub 热点速览 v.21.41」
作者:HelloGitHub-小鱼干 机械臂可能在医疗剧中看过,可以用来执行一些精细化的操作,例如:缝合之类的.但这次 Dummy-Robot 让你不仅看看而已,还具备一定的实操性(有一定的动手.经济 ...
- 【MySQL】MySQL(三)存储过程和函数、触发器、事务
MySQL存储过程和函数 存储过程和函数的概念 存储过程和函数是 事先经过编译并存储在数据库中的一段 SQL 语句的集合 存储过程和函数的好处 存储过程和函数可以重复使用,减轻开发人员的工作量.类似于 ...