您的位置:首页 > 理论基础 > 计算机网络

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;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: