热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

httpclient的简单使用

1、通过get请求后台,注意tomcat的编码设置成utf-8;<ConnectorconnectionTimeout20000port8080protocolHT

1、通过get请求后台,注意tomcat的编码设置成utf-8;   

/** 
* 发送 get请求
*/
public static void get() {
CloseableHttpClient httpclient
= HttpClients.createDefault();
try {
//先将参数放入List,再对参数进行URL编码
List params = new LinkedList();
params.add(
new BasicNameValuePair("get", "get请求哈哈哈"));

//对参数编码
String param = URLEncodedUtils.format(params, "UTF-8");
// 创建httpget.
HttpGet httpget = new HttpGet("http://localhost:8080/HttpServleTest.html?"+param);

// 执行get请求.
CloseableHttpResponse respOnse= httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态码
System.out.println(response.getStatusLine().getStatusCode());
if (entity != null) {
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity,"UTF-8"));
}
}
finally {
response.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// 关闭连接,释放资源
try {
httpclient.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

2.post请求

/** 
* 发送 post
*/
public static void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/HttpServleTest.html");
// 创建参数队列
List formparams = new ArrayList();
formparams.add(
new BasicNameValuePair("post", "post请求哈哈哈"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity
= new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response
= httpclient.execute(httppost);
try {
HttpEntity entity
= response.getEntity();
if (entity != null) {
System.out.println(
"Response content: " + EntityUtils.toString(entity, "UTF-8"));
}
}
finally {
response.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// 关闭连接,释放资源
try {
httpclient.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

3、后台服务程序和本案例代码下载地址:


推荐阅读
author-avatar
书友74972801
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有