Java访问https接口实现
2013-11-14 09:28
471 查看
用两种方式分别实现了,第一种是jdk原生的,代码稍微多点,第二种是基于httpclient4版本的。在我的机器上,访问同一个接口原生的性能要好很多(前者900ms,后者5.7s左右),httpclient主要性能消耗在"HttpResponseres=client.execute(post);",大约占总执行时间的90%。
privatestaticfinalStringMETHOD_POST="POST";
privatestaticfinalStringDEFAULT_CHARSET="utf-8";
publicstaticStringdoPost(Stringurl,Stringparams,Stringcharset,intconnectTimeout,intreadTimeout)throwsException{
Stringctype="application/json;charset="+charset;
byte[]content={};
if(params!=null){
content=params.getBytes(charset);
}
returndoPost(url,ctype,content,connectTimeout,readTimeout);
}
publicstaticStringdoPost(Stringurl,Stringctype,byte[]content,intconnectTimeout,intreadTimeout)throwsException{
HttpsURLConnectionconn=null;
OutputStreamout=null;
Stringrsp=null;
try{
try{
SSLContextctx=SSLContext.getInstance("TLS");
ctx.init(newKeyManager[0],newTrustManager[]{newDefaultTrustManager()},newSecureRandom());
SSLContext.setDefault(ctx);
conn=getConnection(newURL(url),METHOD_POST,ctype);
conn.setHostnameVerifier(newHostnameVerifier(){
@Override
publicbooleanverify(Stringhostname,SSLSessionsession){
returntrue;
}
});
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
}catch(Exceptione){
log.error("GET_CONNECTOIN_ERROR,URL="+url,e);
throwe;
}
try{
out=conn.getOutputStream();
out.write(content);
rsp=getResponseAsString(conn);
}catch(IOExceptione){
log.error("REQUEST_RESPONSE_ERROR,URL="+url,e);
throwe;
}
}finally{
if(out!=null){
out.close();
}
if(conn!=null){
conn.disconnect();
}
}
returnrsp;
}
privatestaticclassDefaultTrustManagerimplementsX509TrustManager{
@Override
publicvoidcheckClientTrusted(X509Certificate[]arg0,Stringarg1)throwsCertificateException{}
@Override
publicvoidcheckServerTrusted(X509Certificate[]arg0,Stringarg1)throwsCertificateException{}
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}
}
privatestaticHttpsURLConnectiongetConnection(URLurl,Stringmethod,Stringctype)
throwsIOException{
HttpsURLConnectionconn=(HttpsURLConnection)url.openConnection();
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept","text/xml,text/javascript,text/html");
conn.setRequestProperty("User-Agent","stargate");
conn.setRequestProperty("Content-Type",ctype);
returnconn;
}
protectedstaticStringgetResponseAsString(HttpURLConnectionconn)throwsIOException{
Stringcharset=getResponseCharset(conn.getContentType());
InputStreames=conn.getErrorStream();
if(es==null){
returngetStreamAsString(conn.getInputStream(),charset);
}else{
Stringmsg=getStreamAsString(es,charset);
if(StringUtils.isEmpty(msg)){
thrownewIOException(conn.getResponseCode()+":"+conn.getResponseMessage());
}else{
thrownewIOException(msg);
}
}
}
privatestaticStringgetStreamAsString(InputStreamstream,Stringcharset)throwsIOException{
try{
BufferedReaderreader=newBufferedReader(newInputStreamReader(stream,charset));
StringWriterwriter=newStringWriter();
char[]chars=newchar[256];
intcount=0;
while((count=reader.read(chars))>0){
writer.write(chars,0,count);
}
returnwriter.toString();
}finally{
if(stream!=null){
stream.close();
}
}
}
privatestaticStringgetResponseCharset(Stringctype){
Stringcharset=DEFAULT_CHARSET;
if(!StringUtils.isEmpty(ctype)){
String[]params=ctype.split(";");
for(Stringparam:params){
param=param.trim();
if(param.startsWith("charset")){
String[]pair=param.split("=",2);
if(pair.length==2){
if(!StringUtils.isEmpty(pair[1])){
charset=pair[1].trim();
}
}
break;
}
}
}
returncharset;
}
publicstaticJSONObjectpost(Stringurl,Stringjson){
HttpClientclient=newDefaultHttpClient();
client=WebClientDevWrapper.wrapClient(client);
HttpPostpost=newHttpPost(url);
JSONObjectresponse=null;
try{
StringEntitys=newStringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
LongstartTime=System.currentTimeMillis();
HttpResponseres=client.execute(post);
System.out.println(System.currentTimeMillis()-startTime);
if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
HttpEntityentity=res.getEntity();
Stringcharset=EntityUtils.getContentCharSet(entity);
if(charset==null){
charset="utf-8";
}
response=newJSONObject(newJSONTokener(
newInputStreamReader(entity.getContent(),charset)));
}
}catch(Exceptione){
thrownewRuntimeException(e);
}
returnresponse;
}
publicstaticclassWebClientDevWrapper{
publicstaticHttpClientwrapClient(HttpClientbase){
try{
SSLContextctx=SSLContext.getInstance("TLS");
X509TrustManagertm=newX509TrustManager(){
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}
@Override
publicvoidcheckClientTrusted(
java.security.cert.X509Certificate[]chain,
StringauthType)
throwsjava.security.cert.CertificateException{
}
@Override
publicvoidcheckServerTrusted(
java.security.cert.X509Certificate[]chain,
StringauthType)
throwsjava.security.cert.CertificateException{
}
};
ctx.init(null,newTrustManager[]{tm},null);
SSLSocketFactoryssf=newSSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManagerccm=base.getConnectionManager();
SchemeRegistrysr=ccm.getSchemeRegistry();
sr.register(newScheme("https",443,ssf));
returnnewDefaultHttpClient(ccm,base.getParams());
}catch(Exceptionex){
ex.printStackTrace();
returnnull;
}
}
}
相关文章推荐
- Java访问https接口实现
- Java访问https接口实现
- Java访问https接口实现(JDK/Httpclient4)
- Java访问https接口实现
- java中访问https接口需要ssl证书的安装
- java+oracle+web(第七天) tomcat介绍 (四)实现https://www.igo.com 直接访问我的主页
- 通过JAVA的net包实现JAVA http接口访问错误总结
- java中接口的定义与实现 Java中几种访问权限总结
- java实现自动化测试接口访问(四)--Postman参数化
- java实现自动化测试接口访问(一)
- java实现自动化测试接口访问(三)--查询书籍的api接口
- JAVA实现http/https的Post、Get、代理访问请求
- java代码使用https访问接口
- JAVA实现HTTPS接口(POST方式)
- java代码实现访问网络外部接口并获取数据的工具类
- 使用Java访问https接口javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
- java实现自动化测试接口访问(二)--Http登录授权接口实例
- Java通过redis实现接口ip访问频率限制
- java用ssl和url共同类实现访问某https网站
- 【java编程思想--学习笔记(三)】访问控制-接口实现与类的访问权限