在很多场景下都需要用到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. libmysqlclient version

    You probably know that the version number of the libmysqlclient.so library has changed from .16 to . ...

  2. 784. Letter Case Permutation

    这个题的思想很重要,两种方法 第一种,回溯法 class Solution { public: int sz; vector<string> letterCasePermutation(s ...

  3. 2019.01.21 洛谷P3919 【模板】可持久化数组(主席树)

    传送门 题意简述:支持在某个历史版本上修改某一个位置上的值,访问某个历史版本上的某一位置的值. 思路: 用主席树直接维护历史版本即可. 代码: #include<bits/stdc++.h> ...

  4. 2018.11.01 NOIP训练 梭哈(模拟)

    传送门 这题貌似不考智商啊. 直接按题意写就可以了. 事实上把牌从小到大排序之后写起来很舒服的. 然后就是有些地方可以人脑减代码量和判断次数. (提示:满堂红和某几种同类型的牌的大小判断) 然后注意A ...

  5. 2018.10.31 bzoj3339&&3585mex(主席树)

    传送门 双倍经验 直接上主席树,每个叶节点维护这个值出现的最右区间,非叶子节点维护当前值域内所有最右区间的最小值. 查询的时候只用在以root[qr]root[qr]root[qr]为根的树上面二分. ...

  6. linux 下安装安装mysql 5.6. 5.7

    linux版本:CentOS7 64位 5.7.20 安装请看 他人博客 我已经安装成功了 https://www.cnblogs.com/cz-xjw/p/8006904.html 5.6安装 前提 ...

  7. linux复制文件并修改文件名

    #!/bin/bash #复制/casnw/backup/db203oradata/目录下的所有后缀名为dmp的文件拷贝到/casnw/backup/dbmonthbak 目录下cp -f /casn ...

  8. hadoop配置分区

    1.运行MR,得出HDFS路径下数据 2.创建 Hive 表 映射 HDFS下的数据 3.为数据创建分区,在hive下执行 source 分区表: TIPS:结果集的时间,必须在分区范围内: 可以理解 ...

  9. UVaLive 3490 Generator (KMP + DP + Gauss)

    题意:随机字母组成一个串,有一个目标串,当这个由随机字母组成的串出现目标串就停止,求这个随机字母组成串的期望长度. 析:由于只要包含目标串就可以停止,所以可以先把这个串进行处理,也就是KMP,然后dp ...

  10. 程序重复报more than 'max_user_connections' active connections问题解决

    早晨,开发扔过来一个问题,截图如下: ums already has more than 'max_user_connections' active connections 查看数据库发现: 最大连接 ...