HttpClient 使用案例
package com.qifeng.config.ygx.common.utils; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; /**
* @author zhao xin
* @Title: HttpClientUtil
* @ProjectName as_configurer
* @Description: TODO
* @date 2019/9/21 13:51
*/
public class HttpClientUtil { //同步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());
} //同步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());
} //异步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());
} //异步的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);
} @SneakyThrows
public static String DoPost(String url, JSONObject params){
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpPost httpPost= new HttpPost(url); List<BasicNameValuePair> list=new ArrayList<>(); if(params!=null) {
if(params.get("Content-Type")!=null){
httpPost.addHeader("Content-Type", params.get("Content-Type").toString());
}
if(params.get("UserName")!=null){
httpPost.addHeader("UserName", params.get("UserName").toString()); }
if(params.get("type")!=null){
JSONObject Json = new JSONObject();
Json.put("type", params.get("type").toString());
StringEntity entity = new StringEntity(Json.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
if(params.get("stationId")!=null){
list.add(new BasicNameValuePair("stationId", params.get("stationId").toString()));
}
} if(params.get("Content-Type")==null) {
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity!=null){
String entityStr= EntityUtils.toString(entity,"utf-8");
return entityStr;
}else{
return null;
}
} }
HttpClient 使用案例的更多相关文章
- HttpClient 应用案例揭破应用Discuss论坛登录
闲来无事,写了一个对discuss论坛登录的案例,初次上场按照以前的惯例没成功,见过抓包分析discuss论坛成功完成,废话不多说 直接上代码. 1:winform 做客户端,添加HttpClient ...
- httpclient的理解(代码理解)
一,httpclient的理解 httpcliet就是模仿浏览器在服务器内部从一个项目调用另一个项目的技术.比如说调用接口等. HttpClient 是 Apache Jakarta Common ...
- SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例
要搭建的项目的项目结构如下(使用的框架为:Spring.SpingMVC.MyBatis): 2.pom.xml中的配置如下(注意,本工程分为几个小的子工程,另外两个工程最终是jar包): 其中 ...
- 07_android入门_採用HttpClient的POST方式、GET方式分别实现登陆案例
1.简单介绍 HttpClient 是 Apache Jakarta Common 下的子项目,能够用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,而且它支持 HTTP 协议 ...
- Android(java)学习笔记211:采用httpclient提交数据(qq登录案例)
1.Apache -Httpclient HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包 ...
- httpclient案例二(调用百度地图的接口)
一,class T package com.http.test; import org.junit.Test; import com.http.BaiduMapProxyService; import ...
- httpclient案例一(调用识别接口)
public Map<String, Object> pictureRecognition(String recotype, MultipartFile imageFile) { Stri ...
- Android(java)学习笔记154:采用HttpClient提交数据(qq登录案例)
1.Apache -Httpclient HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包 ...
- HttpClient方式调用接口的java 简单案例源码+附jar包
1 package com.itNoob.httpClient; import org.apache.commons.httpclient.HttpClient; import org.apache. ...
随机推荐
- oracle中的round()方法的用法
[oracle中的round()方法的用法] Round( ) 函数 传回一个数值,该数值是按照指定的小数位元数进行四舍五入运算的结果 oracle一般常用于计算表空间内存还有多少空间 语法 ROUN ...
- 提升方法(boosting)详解
提升方法(boosting)详解 提升方法(boosting)是一种常用的统计学习方法,应用广泛且有效.在分类问题中,它通过改变训练样本的权重,学习多个分类器,并将这些分类器进行线性组合,提高分类的性 ...
- C/C++通用Makefile
最近的项目又回到了Linux上运行,这就需要在Linux下编译项目,写Makefile针对习惯了Windows的程序员来说是一件痛苦的事,如果有一个通用的Makefile该多好啊,本着这样的目的,我再 ...
- 爬虫那些事儿--Http返回码
由于爬虫的抓取也是使用http协议交互.因此需要了解Http的各种返回码所代表的意义,才能判断爬虫的执行结果. 返回码如下: 100 Continue 初始的请求已经接受,客户应当继续发送请求的其余部 ...
- K-mean matlab 实现代码
一.K均值聚类算法 算法步骤如下: 1.初始化 已知数据集合X,及事先指定聚类的总类数N,在X中随机选取N个对象作为初始的聚类中心. 2.设定迭代终止条件 通常设置最大循环次数或者聚类中心的变化误差. ...
- zmq中的router和dealer
https://segmentfault.com/q/1010000000638839 在zeromq的guide里,它用router/dealer模式做了一个broker client对应ZMQ_R ...
- mysqld_safe A mysqld process already exists
最近修改mysql密码遇到mysqld_safe A mysqld process already exists问题: 解决步骤: 1:ps aux |grep mysql 查看mysql的进程. ...
- vue computed和methods 计算属性和侦听器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- CSS3(@media)判断手机横竖屏
@media all and (orientation : landscape) { h2{color:red;}/*横屏时字体红色*/ } @media all and (orientation : ...
- Spring - @ManagedResource, @ManagedOperation, @ManagedAttribute
总结 通过annotation (@ManagedResource, @ManagedOperation, @ManagedAttribute)注解注册MBean到JMX实现监控java运行状态 参考 ...