接口测试03
前情回顾
get请求和post请求的区别
get请求和post请求没有本质区别,只有协议规定的区别
1.参数位置不同:get请求参数通过网址传递;post请求参数通过消息体传递
2.安全性不同:就用户而言,post请求更安全,post请求把参数放在消息体中可以更好的的保护用户隐私;就服务器而言,get请求更安全,get请求一般用于查询操作,天然幂等,避免为服务器产生脏数据
3.参数长度限制不同:get请求的参数受限于浏览器的地址栏;post请求的参数长度可以认为没有限制
4.发包次数不同:get请求发一次包;post请求发两次包,先发请求行和信息头,等服务器返回状态码100以后,再发消息体
通过HttpClient模拟post请求
1.创建HttpClient
CloseableHttpClient client = HttpClients.createDefault();
2.构建网址
String uri = "";
3.创建请求
HttpPost post = new HttpPost(uri);
4.把参数组合成列表
List list = new ArrayList();
list.add(new BasicNameValuePair("键","值"));
list.add(new BasicNameValuePair("键","值"));
.......
5.把列表转换成消息体类型
Content-Type:application/x-www-form-urlencoded
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
6.为请求设置消息体
post.setEntity(entity);
7.执行请求,获取响应
CloseableHttpResponse response = client.execute(post);
8.检查响应结果
状态行
response.getStatusLine()
信息头
response.getAllHeaders()
消息体
response.getEntity()
练习
新闻头条-新闻头条API _API数据接口_API接口调用_API接口平台-聚合数据
获取新闻头条
代码如下
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;public class TopNews {@Testpublic void testNews() throws IOException {CloseableHttpClient client = HttpClients.createDefault();String uri = "http://v.juhe.cn/toutiao/index";HttpPost post = new HttpPost(uri);List list = new ArrayList();list.add(new BasicNameValuePair("key"," "));list.add(new BasicNameValuePair("type","junshi"));list.add(new BasicNameValuePair("page","1"));list.add(new BasicNameValuePair("page_s
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
