import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class RequestSender {

private static CookieStore cookieStore = new BasicCookieStore();
private static Executor executor = Executor.newInstance().use(cookieStore);

private String url;
private String method;
private Map<String, String> paraMap;
private String bodyString;
private ContentType contentType;
private Map<String, String> headerMap;

static {
loginSsoFirst();
}

public RequestSender(RequestSenderBuilder builder) {
this.url = builder.url;
this.method = builder.method;
this.paraMap = builder.paraMap;
this.bodyString = builder.bodyStr;
this.contentType = builder.contentType;
this.headerMap = builder.headerMap;

}

public static RequestSenderBuilder given() {
return new RequestSender.RequestSenderBuilder();
}

private Request buildRequest() throws IOException {
Request request = null;
if (HttpPost.METHOD_NAME.equals(method)) {
request = Request.Post(url).connectTimeout(5000);
} else if (HttpGet.METHOD_NAME.equals(method)) {
request = Request.Get(url).connectTimeout(5000);
} else if (HttpDelete.METHOD_NAME.equals(method)) {
request = Request.Delete(url).connectTimeout(5000);
} else if (HttpPut.METHOD_NAME.equals(method)) {
request = Request.Put(url).connectTimeout(5000);
}

if (null != paraMap && paraMap.size() != 0) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
paraMap.forEach((k, v) -> {
param.add(new BasicNameValuePair(k, v));
});
request = request.bodyForm(param, Consts.UTF_8);
}
if (null != bodyString && !bodyString.equals("")) {
if (contentType != null) {
throw new IOException("Use bodystr must specify contentType!");
}
request = request.bodyString(bodyString, contentType);
}
if (null != headerMap && headerMap.size() != 0) {
for (Map.Entry<String, String> e : headerMap.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
return request;
}

public RequestResult sendRequest() {
RequestResult r = new RequestResult();
HttpResponse response;
try {
Request request = buildRequest();
response = executor.execute(request).returnResponse();
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK || code == HttpStatus.SC_MOVED_TEMPORARILY) {
r.setSuccess(true);
r.setEntity(response.getEntity());
r.setReponseText(EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
r.setSuccess(false);
r.setErrorMsg("Http Status Code Error:" + code);
}

} catch (IOException e) {
r.setSuccess(false);
r.setErrorMsg(e.getMessage());
e.printStackTrace();
}
return r;
}

public static String getCookieValue(String key) {
return cookieStore.getCookies().stream().filter(u -> u.getName().equals(key)).findFirst().get().getValue();
}

public static void addCookie(String name, String value) {
Cookie cookie = new BasicClientCookie(name, value);
cookieStore.addCookie(cookie);
}

private static void loginSsoFirst() {
try {

Map<String, String> loginInfoMap = ConfigLoader.loadLoginInfo();
if (loginInfoMap == null || loginInfoMap.size() == 0) {
return;
}
Map<String, String> map = new HashMap<String, String>(4);
map.put("username", loginInfoMap.get("user"));
map.put("password", loginInfoMap.get("pwd"));
String url = loginInfoMap.get("url");
RequestResult sendRequest = given().post(url).paraMap(map).when().sendRequest();
System.out.println(sendRequest.getReponseText());
if (!sendRequest.isSuccess()) {
throw new Exception("Login Error:" + sendRequest.getErrorMsg());
}
if (cookieStore.getCookies().size() == 0) {
throw new Exception("Cannot get cookie from reponse");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static class RequestSenderBuilder {

private String url = "";
private String method = "get";
private Map<String, String> paraMap;
private String bodyStr = "";
private ContentType contentType;
public Map<String, String> headerMap;

public RequestSenderBuilder get(String url) {
this.url = url;
this.method = HttpGet.METHOD_NAME;
return this;
}

public RequestSenderBuilder post(String url) {
this.url = url;
this.method = HttpPost.METHOD_NAME;
return this;
}

public RequestSenderBuilder delete(String url) {
this.url = url;
this.method = HttpDelete.METHOD_NAME;
return this;
}

public RequestSenderBuilder put(String url) {
this.url = url;
this.method = HttpPut.METHOD_NAME;
return this;
}

public RequestSenderBuilder paraMap(Map<String, String> paraMap) {
this.paraMap = paraMap;
return this;
}

public RequestSenderBuilder bodyStr(String bodyStr) {
this.bodyStr = bodyStr;
return this;
}

public RequestSenderBuilder contentType(ContentType contentType) {
this.contentType = contentType;
return this;
}

public RequestSenderBuilder headerMap(Map<String, String> map) {
this.headerMap = map;
return this;
}

public RequestSender when() {
return new RequestSender(this);
}
}
}

Httpclient Fluent API简单封装的更多相关文章

  1. HttpClient 之Fluent API 简单使用

    相比于HttpClient 之前的版本,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API. 为了方便使用,Fluen ...

  2. HttpClient Fluent API 高并发优化

    apache的httpcomponents-client 4.2之后提供了一套易于使用的facade API称为Fluent API,对于一般使用场景来说,使用起来非常简便,且性能也有一定保证,因为其 ...

  3. Hbase API 简单封装

    >>>>>>>>>>>>>>>>>>>>>>>>> ...

  4. 简单封装axios api

    可以在代码逻辑中写axios请求,处理请求结果,但是随着项目越来越大,代码会很繁琐,不容易维护,所以,可以把一些在所有请求中都要处理的逻辑抽取出来,封装成api方法.比如每次请求中都要判断是否有权限, ...

  5. .NetCore简单封装基于IHttpClientFactory的HttpClient请求

    IHttpClientFactory是什么?为什么出现了IHttpClientFactory 一.IHttpClientFactory是什么? IHttpClientFactory是.netcore2 ...

  6. HttpClient4.2 Fluent API学习

    相比于HttpClient 之前的版本号,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API. 为了方便使用,Flue ...

  7. Angular:使用service进行http请求的简单封装

    ①使用ng g service services/storage创建一个服务组件 ②在app.module.ts 中引入HttpClientModule模块 ③在app.module.ts 中引入创建 ...

  8. EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

    I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...

  9. FMDB简单封装和使用

    工具:火狐浏览器+SQLite Manager插件 ; Xcode; FMDB库; 效果: 项目地址: https://github.com/sven713/PackFMDB 主要参考这两篇博客: 1 ...

随机推荐

  1. ios开发级联菜单(利用父子控制器--两个菜单封装为两个子控制器来实现)

    一:1:级联菜单可以使用两个tableView来实现,也可以利用父子控制器,两个控制器来实现,根视图控制器作为两个控制器的父控制器,来管理两个子控制器.2:将左右菜单分别交给两个控制器去管理,对于一些 ...

  2. Facial keypoints detection Kaggle 竞赛系列

    3.2# Facial keypoints detection 作者:Stu. Rui QQ: 1026163725 原文链接:http://blog.csdn.net/i_love_home/art ...

  3. 一个好汉一个帮:前端UI改造

    今天是周六,继续工作中. 只是,不是自己亲自参与搞代码,让一起好的同事帮我美化界面. 虽说前端,我也可以搞定, but,but呀,所有的工作都让我来搞,实在是太累太烦了. 前端,样式,目前做很多是模仿 ...

  4. TI_DSP_SRIO - Doorbell原理

    前文介绍到SRIO有多种类型的包,当中包括了Doorbell包,Doorbell是一种高速的通知类型的短消息,包头和携带信息都非常短,用于master srio设备通知slave srio设备,可用于 ...

  5. Warning: file_put_contents(常用单词1.txt): failed to open stream: Invalid argument in

    Warning: file_put_contents(常用单词1.txt): failed to open stream: Invalid argument in 一.总结 1.上述问题是因为Win ...

  6. Android菜鸟的成长笔记(25)——可爱的小闹钟

    摘要: 这一篇主要使用系统为我们提供的一个服务AlarmManager来制作一个Android小闹钟,同时还涉及到了自定义主题.判断第一次启动应用.自定义动画.对话框.制作指导滑动页面等方面.最后形成 ...

  7. Codeforces Round #443 (Div. 2) C: Short Program - 位运算

    传送门 题目大意: 输入给出一串位运算,输出一个步数小于等于5的方案,正确即可,不唯一. 题目分析: 英文题的理解真的是各种误差,从头到尾都以为解是唯一的. 根据位运算的性质可以知道: 一连串的位运算 ...

  8. 如何通过submit提交form表单获取后台传来的返回值

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq_34651764/article/details/76373846 小伙伴是不是遇到过这样的问题 ...

  9. array=nil 和 Array=[[NSMutableArray alloc]init]; 的区别

    情况1: array=nil; [_PayArray addObject:BillDetail]; 此时array还是nil:因为array没有分配地址应该. 情况2: Array=[[NSMutab ...

  10. 用Github账号领Ripple币

    最近随着比特币在互联网上的流行,其他各种电子货币也都增加了曝光率. 昨晚在 v2ex 上看到有人发帖,用 20RMB 换取 2013 年 5 月 1 日前使用过的 github 账号得到的一个验证码. ...