public class WebClient {

    public static final String POST_TYPE_JSON = "json";
public static final String POST_TYPE_MULTI = "multi";
public static final String POST_TYPE_NAME_VALUE = "name_value";
private static final Pattern pageEncodingReg = Pattern.compile("content-type.*charset=([^\">\\\\]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern headerEncodingReg = Pattern.compile("charset=(.+)", Pattern.CASE_INSENSITIVE); private DefaultHttpClient httpClient = new DefaultHttpClient();
private String url;
private HTTPMethod method;
private Response response;
private Map<String, String> headers = new HashMap<String, String>();
private JSONObject parameters = new JSONObject();
private List<FormBodyPart> multipartParameter = new ArrayList<FormBodyPart>();
private String postType; private static final String UTF8 = "utf-8"; public void setMethod(HTTPMethod method) {
this.method = method;
} public void setUrl(String url) {
if (isStringEmpty(url)) {
throw new RuntimeException("[Error] url is empty!");
}
this.url = url;
headers.clear();
parameters.clear();
multipartParameter.clear();
postType = null;
response = null; if (url.startsWith("https://")) {
enableSSL();
} else {
disableSSL();
}
} public Map<String, String> getRequestHeaders() {
return headers;
} public void setRequestHeaders(String key, String value){
headers.put(key, value);
} public void addParameter(String name, Object value){
parameters.put(name, value);
} public void setParameters(JSONObject json){
parameters.clear();
parameters.putAll(json);
} public void setAjaxHeaders(){
setRequestHeaders("Content-Type", "application/json");
} public void setTimeout(int connectTimeout, int readTimeout) {
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
HttpConnectionParams.setSoTimeout(params, readTimeout);
} public Response sendRequest() throws IOException {
if (url == null || method == null) {
throw new RuntimeException("Request exception: URL or Method is null");
} httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse resp = null;
HttpUriRequest req = null; if (method.equals(HTTPMethod.GET)) {
req = new HttpGet(url);
}
else if(method.equals(HTTPMethod.DELETE)){
req = new HttpDelete(url);
}
else if(method.equals(HTTPMethod.PUT)){
req = new HttpPut(url);
if(parameters.size() > 0){
StringEntity entity = new StringEntity(new String(parameters.toString().getBytes("utf-8"), "ISO-8859-1"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
((HttpPut) req).setEntity(entity);
}
}
else {
req = new HttpPost(url); if(POST_TYPE_MULTI.equals(postType) ){
MultipartEntity entity = new MultipartEntity();
for(FormBodyPart bodyPart : multipartParameter){
entity.addPart(bodyPart);
}
((HttpPost) req).setEntity(entity);
}
else if(parameters.size() > 0){
if(POST_TYPE_JSON.equals(postType)){
StringEntity entity = new StringEntity(new String(parameters.toString().getBytes("utf-8"), "ISO-8859-1"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
((HttpPost) req).setEntity(entity);
}
else{
Iterator<String> iterator = parameters.keys();
List<NameValuePair> postParameter = new ArrayList<NameValuePair>();
while(iterator.hasNext()){
String key = iterator.next();
postParameter.add(new BasicNameValuePair(key, parameters.getString(key)));
}
((HttpPost) req).setEntity(new UrlEncodedFormEntity(postParameter, UTF8));
}
}
}
for (Entry<String, String> e : headers.entrySet()) {
req.addHeader(e.getKey(), e.getValue());
}
req.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
resp = httpClient.execute(req);
Header[] header = resp.getAllHeaders();
Map<String, String> responseHeaders = new HashMap<String, String>();
for (Header h : header) {
responseHeaders.put(h.getName(), h.getValue());
}
response = new Response();
response.setCode(resp.getStatusLine().getStatusCode());
response.setHeaders(responseHeaders);
String content = getContent(EntityUtils.toByteArray(resp.getEntity()));
response.setContent(content);
return response;
} private boolean isStringEmpty(String s) {
return s == null || s.length() == 0;
} private String getContent(byte[] bytes) throws IOException {
if (bytes == null) {
throw new RuntimeException("[Error] Can't fetch content!");
}
String headerContentType = null;
if ((headerContentType = response.getHeaders().get("Content-Type")) != null) {
Matcher m1 = headerEncodingReg.matcher(headerContentType);
if (m1.find()) {
return new String(bytes, m1.group(1));
}
} String html = new String(bytes);
Matcher m2 = pageEncodingReg.matcher(html);
if (m2.find()) {
html = new String(bytes, m2.group(1));
}
return html;
} private void enableSSL() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpClient.getConnectionManager().getSchemeRegistry().register(https);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} private void disableSSL() {
SchemeRegistry reg = httpClient.getConnectionManager().getSchemeRegistry();
if (reg.get("https") != null) {
reg.unregister("https");
}
} public DefaultHttpClient getHttpClient() {
return httpClient;
} public enum HTTPMethod {
GET, POST, DELETE, PUT
} // SSL handler (ignore untrusted hosts)
private static TrustManager truseAllManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}; public void setPostType(String postType) {
this.postType = postType;
} public void setMultipartParameter(List<FormBodyPart> multipartParameter) {
this.multipartParameter.clear();
this.multipartParameter.addAll(multipartParameter);
}
}

Java HttpClient的更多相关文章

  1. java httpclient发送json 请求 ,go服务端接收

    /***java客户端发送http请求*/package com.xx.httptest; /** * Created by yq on 16/6/27. */ import java.io.IOEx ...

  2. [Java] HttpClient有个古怪的stalecheck选项

    打开stale check会让每次http请求额外消耗15毫秒.而且stalecheck选项缺省是打开的. 这有必要吗???? 在局域网里面调用web api service的时候会死人的. http ...

  3. Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求

    HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...

  4. java HttpClient 忽略证书的信任的实现 MySSLProtocolSocketFactory

    当不需要任何证书访问https时,java中先实现一个MySSLProtocolSocketFactory类忽略证书的信任 package com.tgb.mq.producer.utils; imp ...

  5. java httpclient post xml demo

    jar archive: http://archive.apache.org/dist/httpcomponents/ 基于httpclient 2.0 final的demo(for jdk1.5/1 ...

  6. JAVA HttpClient进行POST请求(HTTPS)

    目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的p ...

  7. $Java HttpClient库的使用

    (一)简介 HttpClient是Apache的一个开源库,相比于JDK自带的URLConnection等,使用起来更灵活方便. 使用方法可以大致分为如下八步曲: 1.创建一个HttpClient对象 ...

  8. java HttpClient POST请求

    一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...

  9. java HttpClient GET请求

    HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...

  10. java httpclient 跳过证书验证

    import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.Unknow ...

随机推荐

  1. seo小技巧(转载)

    转载自前端网:五行缺火 优化技巧是老师在课堂上教不了你的,而自己也不可能在练习中领悟,最便捷的方法就是听取别人的经验,所以转载一下 SEO要点:1.语义化html标签,用合适的标签嵌套合适的内容,不可 ...

  2. js 刷新页面大全

    一.先来看一个简单的例子: 下面以三个页面分别命名为frame.html.top.html.bottom.html为例来具体说明如何做. frame.html 由上(top.html)下(bottom ...

  3. Delphi-Delete 过程

    过程名称 Delete 所在单元 System 过程原型 procedure Delete ( var Source : string; StartChar : Integer; Count : In ...

  4. 转:Python 与 Excel 不得不说的事

    数据处理是 Python 的一大应用场景,而 Excel 则是最流行的数据处理软件.因此用 Python 进行数据相关的工作时,难免要和 Excel 打交道. 如果仅仅是要以表单形式保存数据,可以借助 ...

  5. MVC中的Ajax(AjaxHelper)

    authour: chenboyi updatetime: 2015-04-30 20:47:49 friendly link:   目录 1,思维导图 2,ActionLink() 3,BeginF ...

  6. block 高级

    //从后往前传值 声明block属性 //copy 目的是 将栈区的block拷贝一份到堆区 @property(nonatomic,copy)void (^sendValueBlock)(id); ...

  7. Sleep的问题

    先上全部源码: using System; using System.Threading; namespace MoveServices { public static class MoveWorke ...

  8. 玩死人不偿命的CLOUDSTACK

    玩过CLOUDSTACK(CS)的人,一定不会陌生下面的LOG: 2013-12-27 18:26:43,861 DEBUG [allocator.impl.FirstFitAllocator] (J ...

  9. COJN 0558 800600带通配符的字符串匹配

    800600带通配符的字符串匹配 难度级别:B: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 通配符是一类键盘字符,当我们不知道真正字符或者 ...

  10. 2015WF有感

    World Final题目连接:http://icpc.baylor.edu/worldfinals/problems/icpc2015.pdf 建议:可以倒序阅读来获得最直观的赛场体验... 2:1 ...