Httpclient Fluent API简单封装

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);
}
}
}

posted on 2018-01-02 15:18  harrell  阅读(2722)  评论(1编辑  收藏  举报