在很多场景下都需要用到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. 155. Min Stack - Unsolved

    https://leetcode.com/problems/min-stack/#/solutions Design a stack that supports push, pop, top, and ...

  2. Navicat for MySQL连接出错:1251

    平台:window10 x64+mysql-8.0.15-winx64+navicat_trial_11.1.20.0(PatchNavicat破解) 错误提示:1251-Client does no ...

  3. 2018.12.22 spoj7258 Lexicographical Substring Search(后缀自动机)

    传送门 samsamsam基础题. 题意简述:给出一个串,询问第kkk大的本质不同的串. 然而这就是弦论的简化版. 我们把samsamsam建出来然后贪心选择就行了. 代码: #include< ...

  4. 关于对话框不能响应OnKeyDown和OnChar函数的一些说明

    (1)现象  在MFC的对话框中,映射了WM_CHAR和WM_KEYDOWN消息响应函数后,还是不能响应OnKeyDown和OnChar. (2)原因  因为MFC在进行设计的时候,这两个消息被对话框 ...

  5. hibernate执行createSQLQuery时字段重名的问题

    hibernate执行createSQLQuery时字段重名的问题 不同表关联 ,表字段重名 =>之前若 as 别名 会自动区分 但有一次签移到新服务器  mysql 5.5上: 若字段重名:重 ...

  6. shell常见命令

    awk awk是个很好用的东西,大量使用在linux系统分析的结果展示处理上.并且可以使用管道, input | awk ''  | output 1.首先要知道形式 awk 'command' fi ...

  7. Oracle修改数据库的日期

    ---Oracle数据库更新时间字段数据时的sql语句---格式化时间插入 update t_invite_activityinfo set endtime=to_date('2019-10-30 1 ...

  8. Language Oriented Programming:下一代编程样式 Part I (翻译)

    原文信息 原文地址 作者信息 Sergey Dmitriev JetBrains Sergey Dmitriev is the cofounder and CEO of JetBrains Inc., ...

  9. mysql查询 根据年月日的查询

    select * from call_loan_info where DATE_FORMAT(create_time,'%Y-%m-%d') = '2017-06-16'

  10. oracle之简单总结

    视图: 作用:是数据库对象,是一个或多个表的或视图中导出的虚表,视图对应的数据并不是存储在视图中,而是存储在数据库中的数据表中. 视图的结构和数据是对数据表进行查询的结果. 优点: 1.简化数据操作. ...