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. DEDE站点从网站根目录移到子目录

    修改DedeCms系统配置参数-站点设置 a.站点根网址修改为:http://域名/子目录 b.网页主页链接:/子目录 修改DedeCms系统配置参数-核心设置 a.安装目录:/子目录 批量修改原数据 ...

  2. 弹出层iframe链接设置

    jQuery 比较方便就是创建删除了,所以创建一个弹出层就是当点击div的时候创建一个新的div利用固定位fixed(与浏览器窗口有关)和z-index覆盖body 并利用opacity设置其透明度产 ...

  3. linux下php上传文件注意

    linux下php上传文件注意1.修改上传目录权限linux 修改某目录下所有所有子目录权限chmod -R 777 html修改某目录为任何用户都用写读执行权限chmod a+rwx html2.设 ...

  4. PHP分页详细讲解

    网上有好多PHP分页的类,但我们要弄明白PHP分页原理才可以学到知识,今天我就带你学制作PHP分页.     1.前言分页显示是一种非常常见的浏览和显示大量数据的方法,属于web编程中最常处理的事件之 ...

  5. JQuery Dialog(JS模态窗口,可拖拽的DIV) 效果实现代码

    效果图 调用示意图   交互示意图 如上图所示,这基本是JQueryDialog的完整逻辑流程了. 1.用户点击模态窗口的“提交”按钮时,调用JQueryDialog.Ok()函数,这个函数对应了用户 ...

  6. MVC 用法小语法摘录

    1.类排除列

  7. 关于索引degree设置的问题

    --并行查询 可以使用并行查询的情况 1. Full table scans, full partition scans, and fast full index scans 2. Index ful ...

  8. 【HDOJ】5154 Harry and Magical Computer

    拓扑排序. /* 5154 */ #include <iostream> #include <cstdio> #include <cstring> #include ...

  9. linux中的cd ..和cd -命令有什么区别?

    cd ..是返回上一层目录, cd -是返回到上一次的工作目录,如果当前目录是/执行cd /usr/local再执行cd ..就是到 /usr而执行cd -就是到/

  10. Java中的局部代码块、构造代码块、静态代码块

    局部代码块: 作用:控制变量的生命周期: 在程序中,当我们已经使用完 x 后,并且在接下来的代码中,不会再用到x,那么就没必要让x 在内存中占用空间了,这用情况下,可以使用 局部代码块,将x及其所设计 ...