httpClient的 Post发送的请求,用 list的数据类型是NameValuePair来封装表单中数据

Post设置请求参数的 a、b、c三个 步骤
a:声明List集合封装表单参数
b:创建表单的entity对象
c:设定表单独的entity到httpPost请求中

 

完整代码


/**设置postMan带参数的Post方式请求
* @version 1.0.0
* @program: recuit_gather
* @description:
* @author: zhangdaxu
* @create: 2020-03-13 17:52
*/
public class httpClientPostParam07Test {

@Test
public void getParam() throws URISyntaxException, UnsupportedEncodingException {
System.out.println("设置postMan带参数的Post方式请求");
//1:创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("http://yun.itheima.com");

System.out.println("http请求信息:"+httpPost); //返回值: http请求信息: GET http://www.itcast.cn HTTP/1.1
//设置请求参数 a、b、c三个 步骤
//a:声明List集合封装表单参数
//b:创建表单的entity对象
//c:设定表单独的entity到httpPost请求中

//a:声明List集合封装表单参数
//声名集合:NameValuepair 是名值对。
List<NameValuePair> parms = new ArrayList<NameValuePair>();
//向集合中添加对象
parms.add(new BasicNameValuePair("keys","Java"));
//b:创建表单的entity对象
//创建表单独的Entity对象,第一个参数是封装好的表单数据,第二个是数据的编码
UrlEncodedFormEntity formEntity= new UrlEncodedFormEntity(parms,"utf8");
//c:设定表单独的entity到httpPost请求中
httpPost.setEntity(formEntity);


// 3:设置请求响应的接收变量,如内容为主及必要信息(host,API,HTTP code,响应code,响应时间等等记录)。
CloseableHttpResponse response=null;
try {
response= httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
//把得到响应的载体内容,传递给变量content
String content = EntityUtils.toString(response.getEntity(), "utf8");
//输出响应内容的长度,暂不输出
System.out.println("响应得到内容长度为:"+content.length());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 

 

//扩散阅读

定义了一个list,该list的数据类型是NameValuePair(简单名称值对节点类型),这个代码多处用于Java像url发送Post请求。在发送post请求时用该list来存放参数。
发送请求的大致过程如下:

String url="http://www.baidu.com";

HttpPost httppost=new HttpPost(url); //建立HttpPost对象

List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一个NameValuePair数组,用于存储欲传送的参数

params.add(new BasicNameValuePair("pwd","2544"));
//添加参数

httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//设置编码

HttpResponse response=new DefaultHttpClient().execute(httppost);
//发送Post,并返回一个HttpResponse对象
posted @ 2020-03-13 17:27  码哥之旅  阅读(5121)  评论(0编辑  收藏  举报