使用httpClient模拟http请求
在很多场景下都需要用到java代码来发送http请求:如和短信后台接口的数据发送,发送数据到微信后台接口中;
这里以apache下的httpClient类来模拟http请求:以get和Post请求为例 分别包含同步和异步请求:
首先例子中的代码用的是maven构建的一个简单的java项目:
同步请求所用到的包是:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
异步请求用到的包是:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.2</version>
</dependency>
这个实例中只需要导入这两个类库即可,如果你希望用单元测试,也可导入junit的jar包:
以下是代码部分:
1:同步get方式的请求 其中 uri 是请求的地址如:http://www.baidu.com
主要http不能省略,否则会报 没有指明协议 的错误 如果需要带数据 则以uri?a=sss 形式即可
public void doGet() throws ClientProtocolException, IOException{
//创建CloseableHttpClient
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
//执行
HttpUriRequest httpGet = new HttpGet(uri);
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity!=null){
String entityStr= EntityUtils.toString(entity,"utf-8");
System.out.println(entityStr);
}
// System.out.println(response.toString());
}
2:同步post请求方式: 请求中需要带的数据通过
httpPost.setEntity(new StringEntity("beppe", "UTF-8"));的方式,
如果需要带的数据是对象的形式,则转化为json字符串格式
public void doPost() throws ClientProtocolException, IOException{
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpPost httpPost= new HttpPost(uri);
httpPost.setEntity(new StringEntity("beppe", "UTF-8"));
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity!=null){
String entityStr= EntityUtils.toString(entity,"utf-8");
System.out.println(entityStr);
}
// System.out.println(response.toString());
}
3:异步get请求:
public void doGetAsyn() throws InterruptedException, ExecutionException{
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
//开启httpclient
httpclient.start();
//开始执行
HttpGet httpGet = new HttpGet(uri);
Future<HttpResponse> future = httpclient.execute(httpGet, null);
HttpResponse httpResponse = future.get();
System.out.println(httpResponse.getStatusLine()+"==="+httpGet.getRequestLine());
}
4:异步的post方式请求:其中可以在回调函数中加入自己的业务逻辑
public static void doPostAsyn(String url,String outStr) throws ParseException, IOException, InterruptedException, ExecutionException{
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
httpAsyncClient.start();
HttpPost httpost = new HttpPost(url);
// httpost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity se=new StringEntity(outStr,"UTF-8");
se.setContentType("application/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpost.setEntity(se);
Future<HttpResponse> future = httpAsyncClient.execute(httpost,null);
System.out.println(future.get().toString());
//String result = EntityUtils.toString(response.getEntity(),"UTF-8");
//jsonObject = JSONObject.fromObject(result);
}
使用httpClient模拟http请求的更多相关文章
- 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView
本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...
- HttpClientUtil [使用apache httpclient模拟http请求]
基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...
- 关于HttpClient模拟浏览器请求的參数乱码问题解决方式
转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...
- HttpClient模拟http请求
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- HttpClient模拟客户端请求实例
HttpClient Get请求: /// <summary> /// Get请求模拟 /// </summary> /// < ...
- httpclient模拟服务器请求
// 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost Ht ...
- httpclient模拟post请求json封装表单数据
好长时间不更博了,主要肚子里没什么好墨水,哈哈.废话不说上代码. public static String httpPostWithJSON(String url) throws Exception ...
- java模拟post请求发送json
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...
- java模拟http请求
java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main.utils; impo ...
随机推荐
- Java基本语法实验报告
题目: Java基本语法 课程名称: JAVA语言程序设计 班 级: 信1705-1 姓 名: 刘雨馨 学号: 20173445 指导教师: ...
- Java日期时间使用总结[转载]
Java日期时间使用总结 一.Java中的日期概述 日期在Java中是一块非常复杂的内容,对于一个日期在不同的语言国别环境中,日期的国际化,日期和时间之间的转换,日期的加减运算,日期的展示格式 ...
- 假期训练五(poj-1077bfs+康拓展开,hdu-2577dp)
题目一:传送门 思路:主要是找到状态, 考虑字母有两种状态,大写和小写, 从小写变为大写的变化方式有两种:保持cap状态,或者按住shift键: 从小写变为大写也有一种变化方式:按住shift键: 看 ...
- centos firewalld 基本操作【转】
1.firewalld的基本使用启动: systemctl start firewalld关闭: systemctl stop firewalld查看状态: systemctl status fire ...
- Win7 MinGW环境测试SDL2.0.3
下载MinGW版的文件 http://www.libsdl.org/release/SDL2-devel-2.0.3-mingw.tar.gz 解压放到mysys下面 运行Makefile mysys ...
- iconfont阿里巴巴矢量图标库批量保存
F12输入——var iconList = document.querySelectorAll('.icon-gouwuche1');for (var i = 0; i < iconList.l ...
- dj django与ajax交互
Ajax简介 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互,传输的数 ...
- Apache hadoop安装配置
1.网络中继更改问题 命令: vi /etc/sysconfig/network-scripts/ifcfg-eth0 需要修改的代码 DEVICE=eth0 HWADDR=00:0C:29:11 ...
- Iframe跨域JavaScript自动适应高度
重点分析: 主域名页面:页面A,页面C 其它域名页面:页面B 步骤: 1.页面A(主域名)通过Iframe(id="iframeB")嵌套页面B(其它域名) 2.页面B(其它域名) ...
- android-基础编程-Dialog
Dialog是一种常见的控件. 设置对话框一般步骤如下: 1.实例化dialog 由于AlertDialog的构造函数的关系,不能直接实例化,需要利用Builder来实例化,如 AlertDialog ...