hjg
2024-02-05 301115d5e96b56cd093eee3fcff2d60a15184162
提交 | 用户 | 时间
58d006 1 package com.mandi.common;
A 2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.nio.charset.Charset;
7 import java.security.KeyStore;
8 import java.security.cert.CertificateException;
9 import java.util.ArrayList;
10 import java.util.List;
11 import java.util.Map;
12 import java.util.Map.Entry;
13
14 import javax.net.ssl.SSLContext;
15
16 import org.apache.http.HttpEntity;
17 import org.apache.http.NameValuePair;
18 import org.apache.http.client.CookieStore;
19 import org.apache.http.client.config.CookieSpecs;
20 import org.apache.http.client.entity.UrlEncodedFormEntity;
21 import org.apache.http.client.methods.CloseableHttpResponse;
22 import org.apache.http.client.methods.HttpGet;
23 import org.apache.http.client.methods.HttpPost;
24 import org.apache.http.client.protocol.HttpClientContext;
25 import org.apache.http.config.Registry;
26 import org.apache.http.config.RegistryBuilder;
27 import org.apache.http.conn.ssl.NoopHostnameVerifier;
28 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
29 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
30 import org.apache.http.conn.util.PublicSuffixMatcher;
31 import org.apache.http.conn.util.PublicSuffixMatcherLoader;
32 import org.apache.http.cookie.CookieSpecProvider;
33 import org.apache.http.entity.ContentType;
34 import org.apache.http.entity.StringEntity;
35 import org.apache.http.entity.mime.MultipartEntityBuilder;
36 import org.apache.http.entity.mime.content.FileBody;
37 import org.apache.http.entity.mime.content.StringBody;
38 import org.apache.http.impl.client.BasicCookieStore;
39 import org.apache.http.impl.client.CloseableHttpClient;
40 import org.apache.http.impl.client.HttpClients;
41 import org.apache.http.impl.cookie.BasicClientCookie;
42 import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
43 import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
44 import org.apache.http.message.BasicNameValuePair;
45 import org.apache.http.ssl.SSLContexts;
46 import org.apache.http.util.EntityUtils;
47 import org.apache.log4j.Logger;
48 import org.springframework.context.annotation.Scope;
49 import org.springframework.stereotype.Service;
50
51 /** 
52  * @author mengly 
53  * @version 创建时间:2015年9月18日 下午7:53:25 
54  * 类说明 :包依赖:httpclient,之所以采用singleton,是因为有hcontext
55  */
56 @Service
57 @Scope("singleton")
58 public class Httpmethod {
59     private Logger log=Logger.getLogger(Httpmethod.class);
60     private HttpClientContext hcontext=null;
61     private CookieStore cookiestore=null;
62     public String keyfile="f:\\tomcat.keystore";
63     public String key="123456";
64     public CloseableHttpClient ssl() {
65         CloseableHttpClient httpclient = null;  
66         try {  
67             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
68             FileInputStream instream = new FileInputStream(new File(keyfile));  
69             try {  
70                 // 加载keyStore d:\\tomcat.keystore    
71                 trustStore.load(instream, key.toCharArray());  
72             } catch (CertificateException e) {  
73                 e.printStackTrace();  
74             } finally {  
75                 try {  
76                     instream.close();  
77                 } catch (Exception ignore) {  
78                 }  
79             }  
80             // 相信自己的CA和所有自签名的证书  
81             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
82             // 只允许使用TLSv1协议  
83             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
84                     SSLConnectionSocketFactory.getDefaultHostnameVerifier());  
85             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
86         }catch(Exception ee){
87             ee.printStackTrace();
88         }
89         return httpclient;
90     }  
91     /**
92      * new ssl();
93      * @return 
94      * @author mengly 
95      * @version 创建时间:2015年10月13日 上午11:21:15
96      */
97     public CloseableHttpClient nssl() {
98         CloseableHttpClient httpclient = null;  
99         try {  
100             SSLContext sslcontext = SSLContexts.createDefault();  
101             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);  
102             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
103         }catch(Exception ee){
104             ee.printStackTrace();
105         }
106         return httpclient;
107     } 
108     public String post(String url,Map<String, String> params)
109     {
110          CloseableHttpClient httpclient = HttpClients.createDefault();
111          HttpPost hp=new HttpPost(url);
112          String re=null;
113          List<NameValuePair> fps=new ArrayList<NameValuePair>();
114          UrlEncodedFormEntity entity=null;
115          if(params!=null)
116          {
117              for (Entry<String, String> en : params.entrySet()) {
118                  fps.add(new BasicNameValuePair(en.getKey(), en.getValue()));
119              }
120          }
121          try {
122              entity=new UrlEncodedFormEntity(fps,"UTF-8");
123              hp.setEntity(entity);
124              CloseableHttpResponse cr=null;
125              if(hcontext!=null)
126                 cr= httpclient.execute(hp, hcontext);
127              else
128                 cr= httpclient.execute(hp);
129              try{
130                  HttpEntity he=cr.getEntity();
131                  if(he!=null)
132                      re=EntityUtils.toString(he,"UTF-8");
133              }catch(Exception ee)
134              {}finally{
135                  cr.close();
136              }
137         } catch (Exception e) {
138             log.info("error");
139         }finally{
140              try {  
141                     httpclient.close();  
142                 } catch (IOException e) {  
143                     e.printStackTrace();  
144                 } 
145         }
146         return re;
147     }
148     
149     public String ssl_post(String url,Map<String, String> params)
150     {
151          CloseableHttpClient httpclient=nssl();
152         // CloseableHttpClient httpclient = HttpClients.createDefault();
153          HttpPost hp=new HttpPost(url);
154          String re=null;
155          List<NameValuePair> fps=new ArrayList<NameValuePair>();
156          UrlEncodedFormEntity entity=null;
157          if(params!=null)
158          {
159              for (Entry<String, String> en : params.entrySet()) {
160                  fps.add(new BasicNameValuePair(en.getKey(), en.getValue()));
161              }
162          }
163          try {
164              entity=new UrlEncodedFormEntity(fps,"UTF-8");
165              hp.setEntity(entity);
166              CloseableHttpResponse cr=null;
167              if(hcontext==null)
168                  cr=httpclient.execute(hp);
169              else
170                  cr=httpclient.execute(hp, hcontext);
171              try{
172                  HttpEntity he=cr.getEntity();
173                  if(he!=null)
174                      re=EntityUtils.toString(he,"UTF-8");
175              }catch(Exception ee)
176              {}finally{
177                  cr.close();
178              }
179         } catch (Exception e) {
180             log.info("error");
181         }finally{
182              try {  
183                     httpclient.close();  
184                 } catch (IOException e) {  
185                     e.printStackTrace();  
186                 } 
187         }
188         return re;
189     }
190     
191     public String ssl_postbody(String url,String body)
192     {
193          CloseableHttpClient httpclient=nssl();
194          HttpPost hp=new HttpPost(url);
195          StringEntity se=new StringEntity(body, Charset.forName("utf-8"));
196          hp.setEntity(se);
197          String re=null;
198          try {
199              CloseableHttpResponse cr=null;
200              if(hcontext==null)
201                  cr=httpclient.execute(hp);
202              else
203                  cr=httpclient.execute(hp, hcontext);
204              try{
205                  HttpEntity he=cr.getEntity();
206                  if(he!=null)
207                      re=EntityUtils.toString(he,"UTF-8");
208              }catch(Exception ee)
209              {}finally{
210                  cr.close();
211              }
212         } catch (Exception e) {
213             log.info("error");
214         }finally{
215              try {  
216                     httpclient.close();  
217                 } catch (IOException e) {  
218                     e.printStackTrace();  
219                 } 
220         }
221         return re;
222     }
223     
224     
225     public String get(String url)
226     {
227          CloseableHttpClient httpclient = HttpClients.createDefault();
228          HttpGet  hp=new HttpGet(url);
229          String re=null;
230          try {
231              CloseableHttpResponse cr=null;
232              if(hcontext==null)
233                  cr=httpclient.execute(hp);
234              else
235                  cr=httpclient.execute(hp, hcontext);
236              try{
237                  HttpEntity he=cr.getEntity();
238                  if(he!=null)
239                      re=EntityUtils.toString(he,"UTF-8");
240              }catch(Exception ee)
241              {}finally{
242                  cr.close();
243              }
244         } catch (Exception e) {
245             e.printStackTrace();
246             log.info("error");
247         }finally{
248              try {  
249                     httpclient.close();  
250                 } catch (IOException e) {  
251                     e.printStackTrace();  
252                 } 
253         }
254         return re;
255     }
256     public String ssl_get(String url)
257     {
258          CloseableHttpClient httpclient =nssl();
259          HttpGet  hp=new HttpGet(url);
260          String re=null;
261          try {
262              CloseableHttpResponse cr=null;
263              if(hcontext==null)
264                  cr=httpclient.execute(hp);
265              else
266                  cr=httpclient.execute(hp, hcontext);
267              try{
268                  HttpEntity he=cr.getEntity();
269                  if(he!=null)
270                      re=EntityUtils.toString(he,"UTF-8");
271              }catch(Exception ee)
272              {}finally{
273                  cr.close();
274              }
275         } catch (Exception e) {
276             e.printStackTrace();
277             log.info("error");
278         }finally{
279              try {  
280                     httpclient.close();  
281                 } catch (IOException e) {  
282                     e.printStackTrace();  
283                 } 
284         }
285         return re;
286     }
287     public String upload(String url,String file)
288     {
289          CloseableHttpClient httpclient = HttpClients.createDefault();
290          HttpPost hp=new HttpPost(url);
291          String re=null;
292          FileBody fb=new FileBody(new File(file));
293          StringBody comment=new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
294          HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", fb).addPart("comment", comment).build();
295          try {
296              hp.setEntity(reqEntity);
297              CloseableHttpResponse cr=    httpclient.execute(hp);
298              try{
299                  HttpEntity he=cr.getEntity();
300                  if(he!=null)
301                      re=EntityUtils.toString(he,"UTF-8");
302                  EntityUtils.consume(he); 
303              }catch(Exception ee)
304              {}finally{
305                  cr.close();
306              }
307         } catch (Exception e) {
308             log.info("error");
309         }finally{
310              try {  
311                     httpclient.close();  
312                 } catch (IOException e) {  
313                     e.printStackTrace();  
314                 } 
315         }
316         return re;
317     }
318     public boolean clearcontext()
319     {
320         this.cookiestore.clear();
321         this.cookiestore=null;
322         this.hcontext=null;
323         System.gc();
324         return true;
325     }
326     public boolean createcontext()
327     {
328         hcontext = HttpClientContext.create();
329         cookiestore=new BasicCookieStore();
330         PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.getDefault();
331         Registry<CookieSpecProvider> registry = RegistryBuilder
332             .<CookieSpecProvider> create()
333             .register(CookieSpecs.DEFAULT, new DefaultCookieSpecProvider(publicSuffixMatcher))
334             .register(CookieSpecs.STANDARD,
335                 new RFC6265CookieSpecProvider(publicSuffixMatcher)).build();
336         hcontext.setCookieSpecRegistry(registry);
337         hcontext.setCookieStore(cookiestore);
338         return true;
339     }
340     
341     public boolean addcookie(String name,String value)
342     {
343         if(this.hcontext==null||this.cookiestore==null)
344             return false;
345         BasicClientCookie bc=new BasicClientCookie(name, value);
346         this.cookiestore.addCookie(bc);
347         return true;
348     }
349     public boolean clearcooike()
350     {
351         if(this.hcontext==null||this.cookiestore==null)
352             return false;
353         cookiestore.clear();
354         return true;
355     }
356     
357     
358 }