HttpPost模拟请求带参方式 Java

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:03   3424   0

导包

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;

代码测试

@Test
public void postParams() {

CloseableHttpClient httpClient = HttpClients.createDefault();

String entityStr = null;
CloseableHttpResponse response = null;

try {

HttpPost httpPost = new HttpPost("传入你需要的URL路径");

/*
* 添加请求参数
*/
// 创建请求参数
List<NameValuePair> list = new LinkedList<>();

BasicNameValuePair param1 = new BasicNameValuePair("参数名", "参数值");
BasicNameValuePair param2 = new BasicNameValuePair("参数名", "参数值");

list.add(param1);
list.add(param2);
// 使用URL实体转换工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entityParam);

// 执行请求
response = httpClient.execute(httpPost);
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
entityStr = EntityUtils.toString(entity, "UTF-8");
System.out.println("lalalal===" + entityStr);

// System.out.println(Arrays.toString(response.getAllHeaders()));

} catch (ClientProtocolException e) {
System.err.println("Http协议出现问题");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析错误");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO异常");
e.printStackTrace();
} finally {
// 释放连接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.err.println("释放连接出错");
e.printStackTrace();
}
}
}

// 打印响应内容
System.out.println("在这儿么 = " + entityStr);

}

最后使用 Junit Test运行 在Console

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP