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

HttpsUtil的get和post方法

2016-10-27 10:04 232 查看
package com.cmos.ebs.util;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.StringWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.security.SecureRandom;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.KeyManager;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.util.EntityUtils;

import com.cmos.core.logger.Logger;

import com.cmos.core.logger.LoggerFactory;

public class HttpsUtil {
private static final String METHOD_POST = "POST";  

    private static final String DEFAULT_CHARSET = "utf-8";  

    private static final int connectTimeout = 6000; 

    private static final int readTimeout = 6000; 

    private static final Logger log = LoggerFactory.getUtilLog(HttpsUtil.class);

    

    

    
public static String doPost(String url, String str) {
String charset = DEFAULT_CHARSET;
String ctype = "application/json;charset=" + charset;
HttpsURLConnection conn = null;
OutputStream out = null;
String rsp = null;
byte[] content = null;
try {
content = str.getBytes(charset);
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() {

public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);

out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
} catch (Exception e) {
log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
} finally {
try {
if (out != null)out.close();
if (conn != null)conn.disconnect();
} catch (Exception e) {
log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
}
}

return rsp;
}  

public static String get(String path) throws Exception{
 HttpsURLConnection httpConn=null;
 BufferedReader in=null;
 try {
  URL url=new URL(path);
  httpConn=(HttpsURLConnection)url.openConnection();

  //读取响应
  if(httpConn.getResponseCode()==200){
   StringBuffer content=new StringBuffer();
   String tempStr="";
   in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
   while((tempStr=in.readLine())!=null){
    content.append(tempStr);
   }
   return content.toString();
  }else{
  log.error("请求出现问题");
  }
 } catch (IOException e) {
 log.error("IOException:", e.getMessage(),e);
 }finally{
  in.close();
  httpConn.disconnect();
 }
 return null;
}
public static String doDelete(String url, String str) {

String charset = DEFAULT_CHARSET;
String ctype = "application/json;charset=" + charset;
HttpsURLConnection conn = null;
OutputStream out = null;
String rsp = null;
byte[] content = null;
try {
content = str.getBytes(charset);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
SSLContext.setDefault(ctx);

conn = getConnection(new URL(url),"DELETE", ctype);
conn.setHostnameVerifier(new HostnameVerifier() {

public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);

out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
} catch (Exception e) {
log.error
4000
("REQUEST_RESPONSE_ERROR, URL = " + url, e);
} finally {

try {
if (out != null)out.close();
if (conn != null)conn.disconnect();
} catch (Exception e) {
log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
}
}

return rsp;

}

  

    private static class DefaultTrustManager implements X509TrustManager {

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
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;  

    }  

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