发送POST请求(HTTP),K-V形式
2024-10-20 00:47:57
/**
* 发送POST请求(HTTP),K-V形式
* @param url
* @param params
* @author Charlie.chen
* @return
*/
public
static
String doPost(String url, Map<string, string=
""
> params) {
// 创建默认的HttpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
try
{
// 定义一个get请求方法
HttpPost httppost =
new
HttpPost(url);
// List<namevaluepair> parameters = new ArrayList<namevaluepair>();
// parameters.add(new BasicNameValuePair("username", userName));
// parameters.add(new BasicNameValuePair("password", password));
// 定义post请求的参数
// 建立一个NameValuePair数组,用于存储欲传送的参数
List<namevaluepair> list =
new
ArrayList<namevaluepair>();
Iterator iterator = params.entrySet().iterator();
while
(iterator.hasNext()) {
Entry<string, string=
""
> elem = (Entry<string, string=
""
>) iterator.next();
list.add(
new
BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if
(list.size() >
0
) {
httppost.setEntity(
new
UrlEncodedFormEntity(list,
"utf-8"
));
}
// httppost.setHeader("Content-type","application/json,charset=utf-8");
// httppost.setHeader("Accept", "application/json");
// 执行post请求,返回response服务器响应对象, 其中包含了状态信息和服务器返回的数据
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
// 使用响应对象, 获得状态码, 处理内容
int
statusCode = httpResponse.getStatusLine().getStatusCode();
if
(statusCode ==
200
) {
// 使用响应对象获取响应实体
HttpEntity entity = httpResponse.getEntity();
// 将响应实体转为字符串
String response = EntityUtils.toString(entity,
"utf-8"
);
return
response;
}
else
{
// log.error("访问失败"+statusCode);
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
try
{
// 关闭连接, 和释放资源
httpclient.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
return
null
;
}
转载:https://www.2cto.com/kf/201611/561147.html
最新文章
- 一些有意思的VR设备介绍
- 在Windows 8.1及IE 11中如何使用HttpWatch
- java 25 - 4 网络编程之 UDP协议传输的代码优化
- 基础学习day02--标识符、关键字、数据类型与运算符
- java的transient
- android学习笔记15——Galley
- OpenGL学习之路(二)
- 【阿里云产品公测】OpenSearch初探
- Linux防火墙配置—SNAT1
- dede被注入后台提示用户名不存在解决方法
- oracle拆分一个连续的字符串
- 如何正确使用const、static、extern
- [c/c++] programming之路(28)、结构体存储和内存对齐+枚举类型+typedef+深拷贝和浅拷贝
- Mysql 一些基本的小东西
- [VUE ERROR] Invalid default value for prop ";slides";: Props with type Object/Array must use a factory function to return the default value
- fiddler学习笔记&;&;基本使用
- jquery生成二维码并实现图片下载
- iptables 工具的使用
- vs 字体
- 转 Cobar使用文档(可用作MySQL大型集群解决方案)