Java HttpClient
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的更多相关文章
- java httpclient发送json 请求 ,go服务端接收
/***java客户端发送http请求*/package com.xx.httptest; /** * Created by yq on 16/6/27. */ import java.io.IOEx ...
- [Java] HttpClient有个古怪的stalecheck选项
打开stale check会让每次http请求额外消耗15毫秒.而且stalecheck选项缺省是打开的. 这有必要吗???? 在局域网里面调用web api service的时候会死人的. http ...
- Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求
HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...
- java HttpClient 忽略证书的信任的实现 MySSLProtocolSocketFactory
当不需要任何证书访问https时,java中先实现一个MySSLProtocolSocketFactory类忽略证书的信任 package com.tgb.mq.producer.utils; imp ...
- java httpclient post xml demo
jar archive: http://archive.apache.org/dist/httpcomponents/ 基于httpclient 2.0 final的demo(for jdk1.5/1 ...
- JAVA HttpClient进行POST请求(HTTPS)
目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的p ...
- $Java HttpClient库的使用
(一)简介 HttpClient是Apache的一个开源库,相比于JDK自带的URLConnection等,使用起来更灵活方便. 使用方法可以大致分为如下八步曲: 1.创建一个HttpClient对象 ...
- java HttpClient POST请求
一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...
- java HttpClient GET请求
HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...
- java httpclient 跳过证书验证
import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.Unknow ...
随机推荐
- jQuery 知识积累
1.select下拉框设置选中项 //设置下拉框第一项为选中项$("#selectId option:first").prop("selected", 'sel ...
- jquery获取元素方式
1 从集合中通过指定的序号获取元素 html: <div> <p>0</p> <p>1</p> <p>2</p> & ...
- codeforces567E. President and Roads
题目大意:总统要回家,会经过一些街道,每条街道都是单向的并且拥有权值.现在,为了让总统更好的回家,要对每一条街道进行操作:1)如果该街道一定在最短路上,则输出“YES”.2)如果该街道修理过后,该边所 ...
- 机器学习(4)之Logistic回归
机器学习(4)之Logistic回归 1. 算法推导 与之前学过的梯度下降等不同,Logistic回归是一类分类问题,而前者是回归问题.回归问题中,尝试预测的变量y是连续的变量,而在分类问题中,y是一 ...
- 转:MySQL导入.sql文件及常用命令
在MySQL Qurey Brower中直接导入*.sql脚本,是不能一次执行多条sql命令的,在mysql中执行sql文件的命令: mysql> source d:/myprogram ...
- 【Oracle】安装
http://www.2cto.com/database/201208/150620.html 呵呵,花了一个多小时,左右把11g安装折腾好了.其中折腾SQL Developer 花了好长时间,总算搞 ...
- cf D. Vessels
http://codeforces.com/contest/371/problem/D 第一遍写的超时了,然后看了别人的代码,思路都是找一个点的根,在往里面加水的时候碗中的水满的时候建立联系.查询的时 ...
- 三个QT咨询公司以及QT5.0的主要特点
三个咨询公司(他们也贡献代码):http://www.kdab.com/http://v-play.net/http://www.ics.com/qt 一个论坛:http://forum.qt.io/ ...
- eclipse能够自动提示变量名.
打开 Eclipse -> Window -> Perferences -> Java -> Editor -> Content Assist,在右边最下面一栏找到 au ...
- LD1-K(求差值最小的生成树)
题目链接 /* *题目大意: *一个简单图,n个点,m条边; *要求一颗生成树,使得其最大边与最小边的差值是所有生成树中最小的,输出最小的那个差值; *算法分析: *枚举最小边,用kruskal求生成 ...