导包
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);
}