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. Java简介(2)-基本概念

    1.抽象类:规定一个或多个抽象方法的类别本身必须定义为abstract,抽象类只是用来派生子类,而不能用它来创建对象 2.final类:又称“最终类”,它只能用来创建对象,而不能被继承,与抽象类刚好相 ...

  2. js学习笔记之:键盘应用

    为了方便用户操作,可以为用户设置(或者屏蔽)功能键,代替使用频率比较高的操作.本次,将学习一下基本的功能键使用方法.键盘和焦点使用.屏蔽按键等知识点,以及一些相关示例: 1 设置按键功能: 功能键主要 ...

  3. yii 标签用法(模板)

    yii模板中的label标签 <?php echo $form->labelEx($model,'name'); ?> 编译后: <label for="Projec ...

  4. MLlib-聚类

    聚类 例子 流聚类 例子 聚类 MLlib支持k-means聚类,一种最常用的聚类方法,将数据点聚成指定数据的簇.MLlib实现了一种k-means++的并行变种,叫做kmeansII.MLlib的实 ...

  5. C程序设计语言练习题1-23

    练习1-23 编写一个删除C语言程序中所有的注释语句.要正确处理带引号的字符串与字符常量.在C语言中,注释不能嵌套. 代码如下: #include <stdio.h> // 包含标准库的信 ...

  6. 实验三:gdb跟踪调试内核从start_kernel到init进程启动

    原创作品转载请注明出处<Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 如果我写的不好或者有误的地方请留言 ...

  7. oracle中字符串的大小比较,字符串与数字的比较和运算

    Oracle比较字符串是根据ASCII码来的,第一个字母的ASCII大小比较如果相等再比较下一个,类推.字符串和数字进行操作是会报异常的,因为类型不一样不能进行比较. Oracle在执行SQL的时候有 ...

  8. Sleep的问题

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

  9. hdu Co-prime

    题意:求出在一个区间[A,B]内与N互质的个数 . 思路: 先求出n的质因子,然后求出与N的质因子不互质的个数然后总个数减去就是.用位运算二进制表示那个因子用到过,实现容斥原理.在1到n之间是c倍数的 ...

  10. 引用 运行asp.net程序时候,编译器错误消息: CS0016: 未能写入输出文件“c:\WINDOWS\Microsoft.NET\Fra

    引用 运行asp.net程序时候,编译器错误消息: CS0016: 未能写入输出文件“c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary A ...