httpclientUtil//http、https

 说明:

  数据格式是json。

  可发送http||https||get||post请求

  1 package clientDemo;
  2 
  3 import java.security.cert.CertificateException;
  4 import java.security.cert.X509Certificate;
  5 import java.util.ArrayList;
  6 import java.util.HashMap;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import javax.net.ssl.SSLContext;
 11 import javax.net.ssl.TrustManager;
 12 import javax.net.ssl.X509TrustManager;
 13 
 14 //import net.sf.json.JSONObject;
 15 
 16 import org.apache.http.HttpResponse;
 17 import org.apache.http.HttpStatus;
 18 import org.apache.http.NameValuePair;
 19 import org.apache.http.client.HttpClient;
 20 import org.apache.http.client.entity.UrlEncodedFormEntity;
 21 import org.apache.http.client.methods.HttpGet;
 22 import org.apache.http.client.methods.HttpPost;
 23 import org.apache.http.conn.ClientConnectionManager;
 24 import org.apache.http.conn.scheme.Scheme;
 25 import org.apache.http.conn.scheme.SchemeRegistry;
 26 import org.apache.http.conn.ssl.SSLSocketFactory;
 27 import org.apache.http.impl.client.DefaultHttpClient;
 28 import org.apache.http.message.BasicNameValuePair;
 29 import org.apache.http.util.EntityUtils;
 30 
 31 import com.alibaba.fastjson.JSONObject;
 32 
 33 //用于进行Https请求的HttpClient
 34 class MySSLClient extends DefaultHttpClient {
 35     public MySSLClient() throws Exception {
 36         super();
 37         SSLContext ctx = SSLContext.getInstance("TLS");
 38         X509TrustManager tm = new X509TrustManager() {
 39             @Override
 40             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 41             }
 42 
 43             @Override
 44             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 45             }
 46 
 47             @Override
 48             public X509Certificate[] getAcceptedIssuers() {
 49                 return null;
 50             }
 51         };
 52         ctx.init(null, new TrustManager[] { tm }, null);
 53         SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 54         ClientConnectionManager ccm = this.getConnectionManager();
 55         SchemeRegistry sr = ccm.getSchemeRegistry();
 56         sr.register(new Scheme("https", 443, ssf));
 57     }
 58 }
 59 
 60 /**
 61  * 
 62  * @author Felix 2017年7月19日
 63  *
 64  */
 65 public class HttpClientDemo {
 66 
 67     public static String sendSmsGet(boolean isHttps, String address, Map<String, String> paramMap) {
 68         // String urlNameString =
 69         // "https://api.weixin.qq.com/sns/userinfo?access_token=TOKEN&openid=OPENID";
 70         StringBuffer urlNameString = new StringBuffer(address);
 71         if (!paramMap.isEmpty()) {
 72             urlNameString.append("?");
 73             for (Map.Entry<String, String> param : paramMap.entrySet()) {
 74                 urlNameString.append(param.getKey()).append("=").append(param.getValue()).append("&");
 75             }
 76         }
 77         String result = "";
 78         try {
 79             // 根据地址获取请求
 80             HttpGet request = new HttpGet(urlNameString.deleteCharAt(urlNameString.length() - 1).toString());// 这里发送get请求
 81             // 获取当前客户端对象
 82             HttpClient httpClient = null;
 83             if (isHttps) {
 84                 httpClient = new MySSLClient();
 85             } else {
 86                 httpClient = new DefaultHttpClient();
 87             }
 88             // 通过请求对象获取响应对象
 89             HttpResponse response = httpClient.execute(request);
 90 
 91             // 判断网络连接状态码是否正常(0--200都数正常)
 92             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
 93                 result = EntityUtils.toString(response.getEntity(), "utf-8");
 94             }
 95         } catch (Exception e) {
 96             e.printStackTrace();
 97         }
 98         return result;
 99         // ....result是用户信息,站内业务以及具体的json转换这里也不写了...
100     }
101 
102     public static String sendSmsPost(boolean isHttps, String address, Map<String, Object> paramMap) {
103         String strResult = "";
104         try {
105             HttpPost httppost = new HttpPost(address);
106             // 获取当前客户端对象
107             HttpClient httpClient = null;
108             if (isHttps) {
109                 httpClient = new MySSLClient();
110             } else {
111                 httpClient = new DefaultHttpClient();
112             }
113 
114             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
115             JSONObject jobj = new JSONObject();
116 //            System.out.println(jobj.toJSON(paramMap));
117 
118             httppost.addHeader("Content-type", "application/x-www-form-urlencoded");
119             nameValuePairs.add(new BasicNameValuePair("data", jobj.toJSONString(paramMap)));
120             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
121 
122             HttpResponse response = httpClient.execute(httppost);
123             if (response.getStatusLine().getStatusCode() == 200) {
124                 /* 读返回数据 */
125                 String conResult = EntityUtils.toString(response.getEntity());
126                 JSONObject sobj = new JSONObject();
127                 Map<String, Object> result = sobj.parseObject(conResult, Map.class);
128                 System.out.println("result-----" + result.toString());
129                 if (!result.isEmpty()) {
130                     strResult += "发送成功";
131                     System.out.println("成功发送sms");
132                 } else {
133                     strResult += "发送失败";
134                 }
135             } else {
136                 String err = response.getStatusLine().getStatusCode() + "";
137                 strResult += "发送失败:" + err;
138                 System.out.println("失败发送");
139             }
140         } catch (Exception e) {
141 //            e.printStackTrace();
142             System.out.println("Exception /"+e.getMessage()+"/"+e.getStackTrace()+"/"+e.getSuppressed());
143         }
144         return strResult;
145     }
146 
147     // main
148     public static void main(String[] args) {
149         Map<String, Object> paramMap = new HashMap<String, Object>();
150         Map<String, String> paramsMap = new HashMap<String, String>();
151         paramMap.put("loginname", "admin");
152         paramMap.put("password", "userName");
153         
154         paramsMap.put("citypinyin", "beijing");
155         switch (3) {
156         case 0:
157             //http  get测试http://apistore.baidu.com/microservice/weather?citypinyin=beijing
158             System.out.println(sendSmsGet(false, "http://apistore.baidu.com/microservice/weather", paramsMap));
159             break;
160         case 1:
161             //http  post测试
162             System.out.println(sendSmsPost(false, "http://localhost:8080/http/server", paramMap));
163             break;
164         case 2:
165             // https get测试"https://localhost:8443/admin/login"
166             System.out.println(sendSmsGet(true, "https://localhost:8443/http/server", paramsMap));
167             break;
168         case 3:
169             // https post测试
170             // System.out.println(sendSmsPost(true,"https://localhost:8443/admin/login", paramMap));
171             System.out.println(sendSmsPost(true, "https://localhost:8443/http/server", paramMap));
172             break;
173         case 4:
174             break;
175         default:
176             System.out.println("defalut");
177         }
178 
179     }
180 }
View Code

 

posted on 2017-07-27 17:38  调适hanxs4  阅读(245)  评论(0)    收藏  举报

导航