码迷,mamicode.com
首页 > 其他好文 > 详细

httpclient

时间:2014-07-16 17:59:42      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:blog   http   java   strong   os   art   

import java.io.BufferedReader;
bubuko.com,布布扣import java.io.IOException;
bubuko.com,布布扣import java.io.InputStream;
bubuko.com,布布扣import java.io.InputStreamReader;
bubuko.com,布布扣import java.io.UnsupportedEncodingException;
bubuko.com,布布扣import java.net.HttpURLConnection;
bubuko.com,布布扣import java.net.InetAddress;
bubuko.com,布布扣import java.net.InetSocketAddress;
bubuko.com,布布扣import java.net.Socket;
bubuko.com,布布扣import java.net.SocketAddress;
bubuko.com,布布扣import java.net.URI;
bubuko.com,布布扣import java.net.URISyntaxException;
bubuko.com,布布扣import java.net.URL;
bubuko.com,布布扣import java.net.URLConnection;
bubuko.com,布布扣import java.net.URLEncoder;
bubuko.com,布布扣import java.net.UnknownHostException;
bubuko.com,布布扣import java.security.KeyManagementException;
bubuko.com,布布扣import java.security.NoSuchAlgorithmException;
bubuko.com,布布扣import java.security.cert.CertificateException;
bubuko.com,布布扣import java.security.cert.X509Certificate;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣import javax.net.SocketFactory;
bubuko.com,布布扣import javax.net.ssl.HostnameVerifier;
bubuko.com,布布扣import javax.net.ssl.HttpsURLConnection;
bubuko.com,布布扣import javax.net.ssl.SSLContext;
bubuko.com,布布扣import javax.net.ssl.SSLSession;
bubuko.com,布布扣import javax.net.ssl.TrustManager;
bubuko.com,布布扣import javax.net.ssl.X509TrustManager;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣import org.apache.http.HttpEntity;
bubuko.com,布布扣import org.apache.http.HttpResponse;
bubuko.com,布布扣import org.apache.http.client.ClientProtocolException;
bubuko.com,布布扣import org.apache.http.client.HttpClient;
bubuko.com,布布扣import org.apache.http.client.methods.HttpGet;
bubuko.com,布布扣import org.apache.http.client.methods.HttpPost;
bubuko.com,布布扣import org.apache.http.conn.ClientConnectionManager;
bubuko.com,布布扣import org.apache.http.conn.ConnectTimeoutException;
bubuko.com,布布扣import org.apache.http.conn.scheme.HostNameResolver;
bubuko.com,布布扣import org.apache.http.conn.scheme.Scheme;
bubuko.com,布布扣import org.apache.http.conn.scheme.SchemeRegistry;
bubuko.com,布布扣import org.apache.http.conn.ssl.SSLSocketFactory;
bubuko.com,布布扣import org.apache.http.entity.StringEntity;
bubuko.com,布布扣import org.apache.http.impl.client.DefaultHttpClient;
bubuko.com,布布扣import org.apache.http.params.HttpConnectionParams;
bubuko.com,布布扣import org.apache.http.protocol.HTTP;
bubuko.com,布布扣import org.apache.http.util.EntityUtils;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣/*
bubuko.com,布布扣 * bubuko.com,布布扣 * 
bubuko.com,布布扣 */
bubuko.com,布布扣public class HttpClientSendPost {
bubuko.com,布布扣private static DefaultHttpClient client;
bubuko.com,布布扣 /** 
bubuko.com,布布扣     * 访问https的网站 
bubuko.com,布布扣     * @param httpclient 
bubuko.com,布布扣     */  
bubuko.com,布布扣    private static void enableSSL(DefaultHttpClient httpclient){  
bubuko.com,布布扣        //调用ssl  
bubuko.com,布布扣         try {  
bubuko.com,布布扣                SSLContext sslcontext = SSLContext.getInstance("TLS");  
bubuko.com,布布扣                sslcontext.init(null, new TrustManager[] { truseAllManager }, null);  
bubuko.com,布布扣                SSLSocketFactory sf = new SSLSocketFactory(sslcontext);  
bubuko.com,布布扣                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
bubuko.com,布布扣                Scheme https = new Scheme("https", sf, 443);  
bubuko.com,布布扣                httpclient.getConnectionManager().getSchemeRegistry().register(https);  
bubuko.com,布布扣            } catch (Exception e) {  
bubuko.com,布布扣                e.printStackTrace();  
bubuko.com,布布扣            }  
bubuko.com,布布扣    }  
bubuko.com,布布扣    /** 
bubuko.com,布布扣     * 重写验证方法,取消检测ssl 
bubuko.com,布布扣     */  
bubuko.com,布布扣    private static TrustManager truseAllManager = new X509TrustManager(){  
bubuko.com,布布扣  
bubuko.com,布布扣        public void checkClientTrusted(  
bubuko.com,布布扣                java.security.cert.X509Certificate[] arg0, String arg1)  
bubuko.com,布布扣                throws CertificateException {  
bubuko.com,布布扣            // TODO Auto-generated method stub  
bubuko.com,布布扣              
bubuko.com,布布扣        }  
bubuko.com,布布扣  
bubuko.com,布布扣        public void checkServerTrusted(  
bubuko.com,布布扣                java.security.cert.X509Certificate[] arg0, String arg1)  
bubuko.com,布布扣                throws CertificateException {  
bubuko.com,布布扣            // TODO Auto-generated method stub  
bubuko.com,布布扣              
bubuko.com,布布扣        }  
bubuko.com,布布扣  
bubuko.com,布布扣        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
bubuko.com,布布扣            // TODO Auto-generated method stub  
bubuko.com,布布扣            return null;  
bubuko.com,布布扣        }  
bubuko.com,布布扣          
bubuko.com,布布扣    }; 
bubuko.com,布布扣/**
bubuko.com,布布扣* HTTP Client Object,used HttpClient Class before(version 3.x),but now the
bubuko.com,布布扣* HttpClient is an interface
bubuko.com,布布扣*/
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣public static String sendXMLDataByGet(String url,String xml){
bubuko.com,布布扣   // 创建HttpClient实例     
bubuko.com,布布扣        if (client == null) {
bubuko.com,布布扣// Create HttpClient Object
bubuko.com,布布扣client = new DefaultHttpClient();
bubuko.com,布布扣enableSSL(client);
bubuko.com,布布扣}
bubuko.com,布布扣        StringBuilder urlString=new StringBuilder();
bubuko.com,布布扣        urlString.append(url);
bubuko.com,布布扣        urlString.append("?");
bubuko.com,布布扣        System.out.println("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
bubuko.com,布布扣        try {
bubuko.com,布布扣urlString.append(URLEncoder.encode( getUTF8XMLString(xml) , "UTF-8" ));
bubuko.com,布布扣} catch (UnsupportedEncodingException e2) {
bubuko.com,布布扣// TODO Auto-generated catch block
bubuko.com,布布扣e2.printStackTrace();
bubuko.com,布布扣}
bubuko.com,布布扣        String urlReq=urlString.toString();
bubuko.com,布布扣        // 创建Get方法实例     
bubuko.com,布布扣        HttpGet httpsgets = new HttpGet(urlReq);
bubuko.com,布布扣
bubuko.com,布布扣        String strRep="";
bubuko.com,布布扣try {
bubuko.com,布布扣HttpResponse response = client.execute(httpsgets);    
bubuko.com,布布扣HttpEntity entity = response.getEntity(); 
bubuko.com,布布扣
bubuko.com,布布扣if (entity != null) 
bubuko.com,布布扣strRep = EntityUtils.toString(response.getEntity());
bubuko.com,布布扣   // Do not need the rest    
bubuko.com,布布扣   httpsgets.abort();    
bubuko.com,布布扣}
bubuko.com,布布扣} catch (ClientProtocolException e) {
bubuko.com,布布扣// TODO Auto-generated catch block
bubuko.com,布布扣e.printStackTrace();
bubuko.com,布布扣} catch (IllegalStateException e) {
bubuko.com,布布扣// TODO Auto-generated catch block
bubuko.com,布布扣e.printStackTrace();
bubuko.com,布布扣} catch (IOException e) {
bubuko.com,布布扣// TODO Auto-generated catch block
bubuko.com,布布扣e.printStackTrace();
bubuko.com,布布扣}  
bubuko.com,布布扣        return strRep;
bubuko.com,布布扣    } 
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣/**
bubuko.com,布布扣* Send a XML-Formed string to HTTP Server by post method
bubuko.com,布布扣
bubuko.com,布布扣* @param url
bubuko.com,布布扣*            the request URL string
bubuko.com,布布扣* @param xmlData
bubuko.com,布布扣*            XML-Formed string ,will not check whether this string is
bubuko.com,布布扣*            XML-Formed or not
bubuko.com,布布扣* @return the HTTP response status code ,like 200 represents OK,404 not
bubuko.com,布布扣*         found
bubuko.com,布布扣* @throws IOException
bubuko.com,布布扣* @throws ClientProtocolException
bubuko.com,布布扣*/
bubuko.com,布布扣public static String sendXMLDataByPost(String url, String xmlData)
bubuko.com,布布扣throws ClientProtocolException, IOException {
bubuko.com,布布扣if (client == null) {
bubuko.com,布布扣// Create HttpClient Object
bubuko.com,布布扣client = new DefaultHttpClient();
bubuko.com,布布扣enableSSL(client);
bubuko.com,布布扣}
bubuko.com,布布扣client.getParams().setParameter("http.protocol.content-charset",
bubuko.com,布布扣HTTP.UTF_8);
bubuko.com,布布扣client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
bubuko.com,布布扣client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
bubuko.com,布布扣client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
bubuko.com,布布扣HTTP.UTF_8);
bubuko.com,布布扣
bubuko.com,布布扣// System.out.println(HTTP.UTF_8);
bubuko.com,布布扣// Send data by post method in HTTP protocol,use HttpPost instead of
bubuko.com,布布扣// PostMethod which was occurred in former version
bubuko.com,布布扣// System.out.println(url);
bubuko.com,布布扣HttpPost post = new HttpPost(url);
bubuko.com,布布扣post.getParams().setParameter("http.protocol.content-charset",
bubuko.com,布布扣HTTP.UTF_8);
bubuko.com,布布扣post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
bubuko.com,布布扣post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
bubuko.com,布布扣post.getParams()
bubuko.com,布布扣.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣// Construct a string entity
bubuko.com,布布扣StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
bubuko.com,布布扣entity.setContentType("text/xml;charset=UTF-8");
bubuko.com,布布扣entity.setContentEncoding("UTF-8");
bubuko.com,布布扣// Set XML entity
bubuko.com,布布扣post.setEntity(entity);
bubuko.com,布布扣// Set content type of request header
bubuko.com,布布扣post.setHeader("Content-Type", "text/xml;charset=UTF-8");
bubuko.com,布布扣// Execute request and get the response
bubuko.com,布布扣HttpResponse response = client.execute(post);
bubuko.com,布布扣HttpEntity entityRep = response.getEntity(); 
bubuko.com,布布扣String strrep="";
bubuko.com,布布扣        if (entityRep != null) {     
bubuko.com,布布扣            strrep = EntityUtils.toString(response.getEntity());
bubuko.com,布布扣            // Do not need the rest    
bubuko.com,布布扣            post.abort();    
bubuko.com,布布扣        }  
bubuko.com,布布扣// Response Header - StatusLine - status code
bubuko.com,布布扣// statusCode = response.getStatusLine().getStatusCode();
bubuko.com,布布扣return strrep;
bubuko.com,布布扣}
bubuko.com,布布扣/**
bubuko.com,布布扣* Get XML String of utf-8
bubuko.com,布布扣
bubuko.com,布布扣* @return XML-Formed string
bubuko.com,布布扣*/
bubuko.com,布布扣public static String getUTF8XMLString(String xml) {
bubuko.com,布布扣// A StringBuffer Object
bubuko.com,布布扣StringBuffer sb = new StringBuffer();
bubuko.com,布布扣sb.append(xml);
bubuko.com,布布扣String xmString = "";
bubuko.com,布布扣try {
bubuko.com,布布扣xmString = new String(sb.toString().getBytes("UTF-8"));
bubuko.com,布布扣} catch (UnsupportedEncodingException e) {
bubuko.com,布布扣// TODO Auto-generated catch block
bubuko.com,布布扣e.printStackTrace();
bubuko.com,布布扣}
bubuko.com,布布扣// return to String Formed
bubuko.com,布布扣return xmString.toString();
bubuko.com,布布扣}
bubuko.com,布布扣}

第二种仿http的不用HttpClient 都是jdk自带的包

bubuko.com,布布扣package org.sp.sc.util;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣import java.io.ByteArrayOutputStream;
bubuko.com,布布扣import java.io.InputStream;
bubuko.com,布布扣import java.net.URL;
bubuko.com,布布扣import java.security.cert.CertificateException;
bubuko.com,布布扣import java.security.cert.X509Certificate;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣import javax.net.ssl.HostnameVerifier;
bubuko.com,布布扣import javax.net.ssl.HttpsURLConnection;
bubuko.com,布布扣import javax.net.ssl.SSLContext;
bubuko.com,布布扣import javax.net.ssl.SSLSession;
bubuko.com,布布扣import javax.net.ssl.SSLSocketFactory;
bubuko.com,布布扣import javax.net.ssl.TrustManager;
bubuko.com,布布扣import javax.net.ssl.X509TrustManager;
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣   /**
bubuko.com,布布扣     * 无视Https证书是否正确的Java Http Client
bubuko.com,布布扣     * 
bubuko.com,布布扣     * 
bubuko.com,布布扣     * @author huangxuebin
bubuko.com,布布扣     *
bubuko.com,布布扣     * @create 2012.8.17
bubuko.com,布布扣     * @version 1.0
bubuko.com,布布扣     */
bubuko.com,布布扣public class HttpsUtil {
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣    /**
bubuko.com,布布扣     * 忽视证书HostName
bubuko.com,布布扣     */
bubuko.com,布布扣    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
bubuko.com,布布扣        public boolean verify(String s, SSLSession sslsession) {
bubuko.com,布布扣            System.out.println("WARNING: Hostname is not matched for cert.");
bubuko.com,布布扣            return true;
bubuko.com,布布扣        }
bubuko.com,布布扣    }
bubuko.com,布布扣
bubuko.com,布布扣     /**
bubuko.com,布布扣     * Ignore Certification
bubuko.com,布布扣     */
bubuko.com,布布扣    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
bubuko.com,布布扣
bubuko.com,布布扣bubuko.com,布布扣        private X509Certificate[] certificates;
bubuko.com,布布扣bubuko.com,布布扣
bubuko.com,布布扣        @Override
bubuko.com,布布扣        public void checkClientTrusted(X509Certificate certificates[],
bubuko.com,布布扣                String authType) throws CertificateException {
bubuko.com,布布扣            if (this.certificates == null) {
bubuko.com,布布扣                this.certificates = certificates;
bubuko.com,布布扣                System.out.println("init at checkClientTrusted");
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣        @Override
bubuko.com,布布扣        public void checkServerTrusted(X509Certificate[] ax509certificate,
bubuko.com,布布扣                String s) throws CertificateException {
bubuko.com,布布扣            if (this.certificates == null) {
bubuko.com,布布扣                this.certificates = ax509certificate;
bubuko.com,布布扣                System.out.println("init at checkServerTrusted");
bubuko.com,布布扣            }bubuko.com,布布扣
bubuko.com,布布扣//            for (int c = 0; c < certificates.length; c++) {
bubuko.com,布布扣//                X509Certificate cert = certificates[c];
bubuko.com,布布扣//                System.out.println(" Server certificate " + (c + 1) + ":");
bubuko.com,布布扣//                System.out.println("  Subject DN: " + cert.getSubjectDN());
bubuko.com,布布扣//                System.out.println("  Signature Algorithm: "
bubuko.com,布布扣//                        + cert.getSigAlgName());
bubuko.com,布布扣//                System.out.println("  Valid from: " + cert.getNotBefore());
bubuko.com,布布扣//                System.out.println("  Valid until: " + cert.getNotAfter());
bubuko.com,布布扣//                System.out.println("  Issuer: " + cert.getIssuerDN());
bubuko.com,布布扣//            }
bubuko.com,布布扣bubuko.com,布布扣
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣        @Override
bubuko.com,布布扣        public X509Certificate[] getAcceptedIssuers() {
bubuko.com,布布扣            // TODO Auto-generated method stub
bubuko.com,布布扣            return null;
bubuko.com,布布扣        }
bubuko.com,布布扣bubuko.com,布布扣    };
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣    public static String getMethod(String urlString) {
bubuko.com,布布扣
bubuko.com,布布扣bubuko.com,布布扣        ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
bubuko.com,布布扣        try {
bubuko.com,布布扣bubuko.com,布布扣            URL url = new URL(urlString);
bubuko.com,布布扣bubuko.com,布布扣            /*
bubuko.com,布布扣             * use ignore host name verifier
bubuko.com,布布扣             */
bubuko.com,布布扣            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
bubuko.com,布布扣            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣            // Prepare SSL Context
bubuko.com,布布扣            TrustManager[] tm = { ignoreCertificationTrustManger };
bubuko.com,布布扣            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
bubuko.com,布布扣            sslContext.init(null, tm, new java.security.SecureRandom());
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣            // 从上述SSLContext对象中得到SSLSocketFactory对象
bubuko.com,布布扣            SSLSocketFactory ssf = sslContext.getSocketFactory();
bubuko.com,布布扣            connection.setSSLSocketFactory(ssf);
bubuko.com,布布扣            
bubuko.com,布布扣            InputStream reader = connection.getInputStream();
bubuko.com,布布扣            byte[] bytes = new byte[512];
bubuko.com,布布扣            int length = reader.read(bytes);
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣            do {
bubuko.com,布布扣                buffer.write(bytes, 0, length);
bubuko.com,布布扣                length = reader.read(bytes);
bubuko.com,布布扣            } while (length > 0);
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣            // result.setResponseData(bytes);
bubuko.com,布布扣            System.out.println(buffer.toString());
bubuko.com,布布扣            reader.close();
bubuko.com,布布扣            
bubuko.com,布布扣            connection.disconnect();
bubuko.com,布布扣        } catch (Exception ex) {
bubuko.com,布布扣            ex.printStackTrace();
bubuko.com,布布扣        } finally {
bubuko.com,布布扣        }
bubuko.com,布布扣        String repString= new String (buffer.toByteArray());
bubuko.com,布布扣        return repString;
bubuko.com,布布扣    }
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣//    public static void main(String[] args) {
bubuko.com,布布扣//        String urlString = "https://218.202.0.241:8081/XMLReceiver";
bubuko.com,布布扣//        String output = new String(HttpsUtil.getMethod(urlString));
bubuko.com,布布扣//        System.out.println(output);
bubuko.com,布布扣//    }
bubuko.com,布布扣}
bubuko.com,布布扣

httpclient,布布扣,bubuko.com

httpclient

标签:blog   http   java   strong   os   art   

原文地址:http://www.cnblogs.com/guoyuqiangf8/p/3847477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!