All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.eshore.tools.HTTP Maven / Gradle / Ivy
package com.eshore.tools;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.eshore.tools.JsonString;
public class HTTP {
public final static Charset utf8=Charset.forName("utf-8");
private String url;
public HTTP(String url) {
this.url=url;
}
public HTTP() {}
long begin=0;
public HTTP url(String url) {
begin=System.currentTimeMillis();
this.url=url;
return this;
}
public HTTP postForm(Object param) {
this.header("Content-Type","application/x-www-form-urlencoded");
this.post(FormString.asForm(param));
return this;
}
public HTTP get() {
try {
StringBuilder sb = new StringBuilder();
if(param!=null&¶m.size()>0) {
boolean isFirst=true;
for(Entry e : param.entrySet()) {
if(isFirst) {isFirst=false;}else {sb.append("&");}
sb.append(e.getKey()).append("=").append(e.getValue());
}
if(url.indexOf('?')>-1) {
url+="&"+sb;
}else {
url+="?"+sb;
}
}
open("GET");
conn.setDoOutput(false);
} catch (Exception e) {
error=true;
errMsg="can not access :"+url+" msg:"+e.getMessage();
e.printStackTrace();
}
return this;
}
public HTTP post() {
post(param);
return this;
}
public HTTP post(File o) {
return this;
}
public HTTP post(Object o) {
if(o!=null)
post(JsonString.asJsonString(o));
return this;
}
public HTTP post(String o) {
if(o!=null)
post(o.getBytes(utf8));
return this;
}
OutputStream out;
public HTTP post(byte[] bytes) {
if(bytes!=null)
try {
if(isHTTPS(url)) {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
URL uri =new URL(url);
conn = (HttpURLConnection) uri.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
setHeaders(conn,this.headers);
if(headers==null||!headers.containsKey("Content-Type"))
conn.setRequestProperty("Content-Type","text/json");
conn.connect();
OutputStream out =conn.getOutputStream();
out.write(bytes);
out.close();
int status = conn.getResponseCode();
} catch (Exception e) {
error=true;
errMsg="can not access :"+url+" nmsg:"+e.getMessage();
byte[] eb =getError(conn);
if(eb!=null&&eb.length>0)
errMsg+=new String(getError(conn),utf8);
System.err.println(errMsg);
e.printStackTrace();
}
return this;
}
private byte[] getError(HttpURLConnection conn) {
try {
InputStream in=conn.getErrorStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b= new byte[1024];
int len=0;
while((len=in.read(b))>0) {
bos.write(b, 0, len);
}
in.close();
in=null;
if(out!=null) {
out.close();
}
out=null;
byte[] bs =bos.toByteArray();
bos.close();
return bs;
}catch(Exception ex) {
return null;
//return ex.getMessage();
}finally {
try {
conn.disconnect();
}catch(Exception e) {}
}
}
private static void setHeaders(HttpURLConnection conn,Mapheader){
if(header==null)return;
for(Object o: header.entrySet()){
Entry entry =(Entry)o;
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
public HTTP param(Map param) {
this.param.putAll(param);
return this;
}
public HTTP header(Map param) {
headers.putAll(param);
return this;
}
HashMapparam= new HashMap();
public HTTP param(String k,String v) {
param.put(k, v);
return this;
}
HashMapheaders= new HashMap();
public HTTP header(String k ,String v) {
headers.put(k, v);
return this;
}
public String asString() {
return asString(utf8);
}
public String asString(Charset charset) {
if(this.error)return "{code:\"-1\",msg:\""+errMsg+"\"}";
return new String(asBytes(),charset);
}
InputStream in;
boolean error=false;
String errMsg="";
public byte[] asBytes() {
try {
in=conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b= new byte[1024];
int len=0;
while((len=in.read(b))>0) {
bos.write(b, 0, len);
}
in.close();
in=null;
if(out!=null) {
out.close();
}
out=null;
byte[] bs =bos.toByteArray();
bos.close();
return bs;
} catch (IOException e) {
error=true;
in = conn.getErrorStream();
byte[] b = new byte[2048];
try {
int len = in.read(b);
System.out.println(new String(b,0,len));
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
errMsg=e.getMessage();
e.printStackTrace();
}finally {
spandTime=System.currentTimeMillis()-this.begin;
if(spandTime>3000) {
System.out.println(" slowUrl:"+this.url+" time:"+spandTime);
}
}
return new byte[0];
}
long spandTime;
HttpURLConnection conn;
private void open(String method) throws Exception {
URL httpurl=null;
if(isHTTPS(url)) {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
httpurl= new URL(url);
conn = (HttpURLConnection) httpurl.openConnection();
conn.setRequestMethod(method);// POST GET PUT DELETE
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
if(headers!=null&&headers.size()>0) {
for(Entry e : headers.entrySet()) {
conn.setRequestProperty(e.getKey(), e.getValue());
}
}
}
public String getResponseHeader(String k) {
return conn.getHeaderField(k);
}
public boolean isHTTPS(String url) {
if(url.toLowerCase().startsWith("https"))return true;
return false;
}
int connectTimeout=1000;
public HTTP setConnectTimeout(int timeout) {
connectTimeout=timeout;
return this;
}
int readTimeout=6000;
public HTTP setReadTimeout(int timeout) {
readTimeout=timeout;
return this;
}
public HTTP basic(String account,String passwd) {
this.header("authorization","Basic "+B64.encode((account+":"+passwd).getBytes()));
return this;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new HTTP("https://www.baidu.com").get().asString());
System.out.println(new HTTP("https://www.163.com").get().asString());
System.out.println(new HTTP("http://127.0.0.1:84/svn/")
.basic("eric", "123456")
.get().asString(Charset.forName("GBK")));
}
static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
public class NullHostNameVerifier implements HostnameVerifier {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
}
}