2
3 importjavax.net.ssl.SSLContext;4 importjavax.net.ssl.TrustManager;5 importjavax.net.ssl.X509TrustManager;6
7 importorg.apache.http.HttpEntity;8 importorg.apache.http.HttpHost;9 importorg.apache.http.HttpResponse;10 importorg.apache.http.auth.AuthScope;11 importorg.apache.http.auth.UsernamePasswordCredentials;12 importorg.apache.http.client.AuthCache;13 importorg.apache.http.client.methods.HttpPost;14 importorg.apache.http.client.protocol.ClientContext;15 importorg.apache.http.conn.scheme.Scheme;16 importorg.apache.http.conn.ssl.SSLSocketFactory;17 importorg.apache.http.entity.StringEntity;18 importorg.apache.http.impl.auth.BasicScheme;19 importorg.apache.http.impl.client.BasicAuthCache;20 importorg.apache.http.impl.client.DefaultHttpClient;21 importorg.apache.http.params.CoreConnectionPNames;22 importorg.apache.http.protocol.BasicHttpContext;23 importorg.apache.http.util.EntityUtils;24
25
26 /**
27 *@authorkobe28 *29 */
30 public classTesthttps {31
32 public static final String username = "";33 public static final String password = "";34 public static final String ip = "";35 public static final int port = 443;36
37 /**
38 *39 *@paramrequestUrl40 *@paramxmlData41 *@paramcontentType42 *@paramcharset43 */
44 public voidpostRequest(String requestUrl, String xmlData, String contentType, String charset)45 {46
47 int returncode = 0;48 String msg = "";49 //1. 创建HttpClient对象。
50 DefaultHttpClient httpClient = newDefaultHttpClient();51 //2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
52 HttpPost post = newHttpPost(requestUrl);53 try
54 {55 //3. 如果需要发送请求参数,
56 StringEntity entity = newStringEntity(xmlData, charset);57 entity.setContentType(contentType);58 post.setEntity(entity);59 //3.1访问https的网站设置ssl
60 enableSSL(httpClient);61 //3.2设置超时
62 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000);63 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);64 //3.3设置basic基本认证
65 BasicHttpContext basicHttpContext =enableBasic(httpClient, username, password, ip, port);66 //4. 调用HttpClient对象的execute
67 HttpResponse response =httpClient.execute(post, basicHttpContext);68 //5. 调用HttpResponse的getAllHeaders()、getHeaders(String69 //name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
70 returncode =response.getStatusLine().getStatusCode();71 System.out.println("postCode= " +returncode);72 //若状态值为2类,则ok
73 if (200<=returncode&&returncode<300)74 {75 System.out.println("数据发送成功!");76 }77 else{78 HttpEntity entityRep =response.getEntity();79 if (entityRep != null)80 {81 msg = EntityUtils.toString(response.getEntity(),"UTF-8");82 System.out.println("错误信息"+msg);83
84 }85
86 }87
88 }89 catch(Exception e)90 {91 e.printStackTrace();92 }93 finally
94 {95 //关闭连接释放资源
96 if (null !=post)97 {98 post.releaseConnection();99
100 }101 if (null !=httpClient)102 {103 httpClient.getConnectionManager().shutdown();104 }105
106 }107
108 }109
110
111
112
113 public BasicHttpContext enableBasic(DefaultHttpClient httpClient,String username,String password,String ip, intport)114 {115 AuthScope authScope = newAuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);116 UsernamePasswordCredentials credentials = newUsernamePasswordCredentials(username, password);117 httpClient.getCredentialsProvider().setCredentials(authScope, credentials);118 //Create AuthCache instance
119 AuthCache authCache = newBasicAuthCache();120 //Generate BASIC scheme object and add it to the local auth cache
121 BasicScheme basicAuth = newBasicScheme();122 HttpHost targetHost = new HttpHost(ip, port, "https");123 authCache.put(targetHost, basicAuth);124 //Add AuthCache to the execution context
125 BasicHttpContext localcontext = newBasicHttpContext();126 localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);127
128 returnlocalcontext;129 }130
131 /**
132 * 访问https的网站133
134 *135 *@paramhttpclient136 */
137 public voidenableSSL(DefaultHttpClient httpclient)138 {139 //调用ssl
140 try
141 {142 SSLContext sslcontext = SSLContext.getInstance("TLS");143 sslcontext.init(null, new TrustManager[] { truseAllManager }, null);144 SSLSocketFactory sf = newSSLSocketFactory(sslcontext);145 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);146 Scheme https = new Scheme("https", sf, 443);147 httpclient.getConnectionManager().getSchemeRegistry().register(https);148 }149 catch(Exception e)150 {151 e.printStackTrace();152 }153 }154
155 /**
156 * 重写验证方法,取消检测ssl157 */
158 public TrustManager truseAllManager = newX509TrustManager() {159
160 publicjava.security.cert.X509Certificate[] getAcceptedIssuers()161 {162 return null;163 }164
165 @Override166 public voidcheckClientTrusted(java.security.cert.X509Certificate[] chain, String authType)167 throwsjava.security.cert.CertificateException168 {169 }170
171 @Override172 public voidcheckServerTrusted(java.security.cert.X509Certificate[] chain, String authType)173 throwsjava.security.cert.CertificateException174 {175 }176
177 };178
179 }