在很多场景下都需要用到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请求的更多相关文章

  1. 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView

    本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...

  2. HttpClientUtil [使用apache httpclient模拟http请求]

    基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...

  3. 关于HttpClient模拟浏览器请求的參数乱码问题解决方式

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...

  4. HttpClient模拟http请求

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  5. HttpClient模拟客户端请求实例

    HttpClient Get请求: /// <summary>        /// Get请求模拟        /// </summary>        /// < ...

  6. httpclient模拟服务器请求

    // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost Ht ...

  7. httpclient模拟post请求json封装表单数据

    好长时间不更博了,主要肚子里没什么好墨水,哈哈.废话不说上代码. public static String httpPostWithJSON(String url) throws Exception ...

  8. java模拟post请求发送json

    java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...

  9. java模拟http请求

    java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main.utils; impo ...

随机推荐

  1. NYOJ 1016 判断两线段是否相交

    #include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #inc ...

  2. PHP array

    一.数组操作的基本函数 数组的键名和值 array_values($arr);获得数组的值 array_keys($arr);获得数组的键名 array_flip($arr);数组中的值与键名互换(如 ...

  3. hdu 1540(线段树区间合并)

    题目链接:传送门 参考文章:传送门 题意:n个数字初始连在一条线上,有三种操作, D x表示x号被摧毁: R 表示恢复剩下的通路 Q表示查询标号为x所在的串的最长长度. 思路:线段树的区间合并. #i ...

  4. pat -1004(树的遍历)

    题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184 思路: (1)用vector记录每 ...

  5. Router components

    Input Unit The Input unit contains virtual channel buffers and an input VC arbiter. Route Info: use ...

  6. linux source命令的用法

    source命令用法:source FileName作用:在当前bash环境下读取并执行FileName中的命令.(如把ls写入a.txt,然后source a.txt 就会执行ls命令,列出目录)注 ...

  7. ArcGIS 关于Web_Mercator

    #小知识#EPSG,即 European Petroleum Standards Group 欧洲石油标准组织 在ArcGIS 10中Web Mercator有三种EPSG编号.他们分别是EPSG38 ...

  8. css3实现卡牌旋转与物体发光效果

    效果演示 http://demo.qpdiy.com/hxw/CSS3/rotate+light.html 物体旋转: 卡牌同一位置放2张图片,通过设置3D动画旋转实现 animation: card ...

  9. POJ3258--River Hopscotch(Binary Search similar to POJ2456)

    Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully ...

  10. ubuntu 开机自启(2B的经历)

    上午写了很细致的开机自启说明文档(需打开terminal进行输出认证).睡了一下午,回来楼主说,联想PM要用Ubuntu Server 当服务器,必须用命令行实现.. 连续各种百度谷歌,看了N多文档, ...