Java访问https接口实现
2014-04-02 11:40
405 查看
用两种方式分别实现了,第一种是jdk原生的,代码稍微多点,第二种是基于httpclient4版本的。在我的机器上,访问同一个接口原生的性能要好很多(前者900ms,后者5.7s左右),httpclient主要性能消耗在"HttpResponse res = client.execute(post);",大约占总执行时间的90%。
Java代码
private static final String METHOD_POST = "POST";
private static final String DEFAULT_CHARSET = "utf-8";
public static String doPost(String url, String params, String charset, int connectTimeout, int readTimeout) throws Exception {
String ctype = "application/json;charset=" + charset;
byte[] content = {};
if(params != null){
content = params.getBytes(charset);
}
return doPost(url, ctype, content, connectTimeout, readTimeout);
}
public static String doPost(String url, String ctype, byte[] content,int connectTimeout,int readTimeout) throws Exception {
HttpsURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
conn = getConnection(new URL(url), METHOD_POST, ctype);
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
}catch(Exception e){
log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
throw e;
}
try{
out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
}catch(IOException e){
log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
throw e;
}
}finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
private static HttpsURLConnection getConnection(URL url, String method, String ctype)
throws IOException {
HttpsURLConnection conn = (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);
return conn;
}
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
StringWriter writer = new StringWriter();
char[] chars = new char[256];
int count = 0;
while ((count = reader.read(chars)) > 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET;
if (!StringUtils.isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : 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;
}
}
}
return charset;
}
Java代码
public static JSONObject post(String url, String json) {
HttpClient client = new DefaultHttpClient();
client = WebClientDevWrapper.wrapClient(client);
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
Long startTime = System.currentTimeMillis();
HttpResponse res = client.execute(post);
System.out.println(System.currentTimeMillis() - startTime);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
if(charset == null){
charset = "utf-8";
}
response = new JSONObject(new JSONTokener(
new InputStreamReader(entity.getContent(), charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
public static class WebClientDevWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
Java代码
private static final String METHOD_POST = "POST";
private static final String DEFAULT_CHARSET = "utf-8";
public static String doPost(String url, String params, String charset, int connectTimeout, int readTimeout) throws Exception {
String ctype = "application/json;charset=" + charset;
byte[] content = {};
if(params != null){
content = params.getBytes(charset);
}
return doPost(url, ctype, content, connectTimeout, readTimeout);
}
public static String doPost(String url, String ctype, byte[] content,int connectTimeout,int readTimeout) throws Exception {
HttpsURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
conn = getConnection(new URL(url), METHOD_POST, ctype);
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
}catch(Exception e){
log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
throw e;
}
try{
out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
}catch(IOException e){
log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
throw e;
}
}finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
private static HttpsURLConnection getConnection(URL url, String method, String ctype)
throws IOException {
HttpsURLConnection conn = (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);
return conn;
}
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
StringWriter writer = new StringWriter();
char[] chars = new char[256];
int count = 0;
while ((count = reader.read(chars)) > 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET;
if (!StringUtils.isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : 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;
}
}
}
return charset;
}
Java代码
public static JSONObject post(String url, String json) {
HttpClient client = new DefaultHttpClient();
client = WebClientDevWrapper.wrapClient(client);
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
Long startTime = System.currentTimeMillis();
HttpResponse res = client.execute(post);
System.out.println(System.currentTimeMillis() - startTime);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
if(charset == null){
charset = "utf-8";
}
response = new JSONObject(new JSONTokener(
new InputStreamReader(entity.getContent(), charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
public static class WebClientDevWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
相关文章推荐
- Java访问https接口实现(JDK/Httpclient4)
- Java访问https接口实现
- Java访问https接口实现
- Java访问https接口实现
- java代码实现访问网络外部接口并获取数据的工具类
- JAVA实现http/https的Post、Get、代理访问请求
- java代码使用https访问接口
- JAVA实现HTTPS接口(POST方式)
- 使用Java访问https接口javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
- java实现自动化测试接口访问(二)--Http登录授权接口实例
- 【java编程思想--学习笔记(三)】访问控制-接口实现与类的访问权限
- Java通过redis实现接口ip访问频率限制
- 在华为实现的java访问https,多线程,写日志
- Java实现https访问
- java用ssl和url共同类实现访问某https网站
- Java访问Https接口
- java中访问https接口需要ssl证书的安装
- java中接口的定义与实现 Java中几种访问权限总结
- java+oracle+web(第七天) tomcat介绍 (四)实现https://www.igo.com 直接访问我的主页
- 通过JAVA的net包实现JAVA http接口访问错误总结