码迷,mamicode.com
首页 > 编程语言 > 详细

Java的post(HTTPS)请求-----接口测试

时间:2018-05-18 11:31:26      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:amp   错误   rand   key   context   OLE   buffere   必须   use   

这个是忽略证书的办法

  1 package com.ju.util;
  2 
  3 
  4 import java.io.BufferedReader;
  5 import java.io.IOException;
  6 
  7 import java.io.InputStreamReader;
  8 import java.io.OutputStream;
  9 import java.io.OutputStreamWriter;
 10 import java.io.PrintWriter;
 11 import java.net.HttpURLConnection;
 12 import java.net.URL;
 13 import java.util.Map;
 21 import javax.net.ssl.HostnameVerifier;
 22 import javax.net.ssl.HttpsURLConnection;
 23 import javax.net.ssl.SSLContext;
 24 import javax.net.ssl.SSLSession;
 25 import javax.net.ssl.TrustManager;
 32 import net.sf.json.JSONObject;
 34 import java.security.cert.X509Certificate;  
 36 import javax.net.ssl.X509TrustManager;  
 public class HttpPost {
 41     
 42       
 43     private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
 44         public boolean verify(String hostname, SSLSession session) {
 45             return true;
 46         }
 47     };
 48 
 49     private static void trustAllHosts() {
 50         // Create a trust manager that does not validate certificate chains
 51         TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
 52             public java.security.cert.X509Certificate[] getAcceptedIssuers() {
 53                 return new java.security.cert.X509Certificate[]{};
 54             }
 55 
 56             public void checkClientTrusted(X509Certificate[] chain, String authType) {
 57             }
 58 
 59             public void checkServerTrusted(X509Certificate[] chain, String authType) {
 60             }
 61         }};
 62         // Install the all-trusting trust manager
 63         try {
 64             SSLContext sc = SSLContext.getInstance("TLS");
 65             sc.init(null, trustAllCerts, new java.security.SecureRandom());
 66             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 67         } catch (Exception e) {
 68             e.printStackTrace();
 69         }
 70     }
 71 
 72     public static   String https(String url, Map<String, String> params) throws Exception {
 73         // 构建请求参数
 74                 String result = "";
 75                 PrintWriter out = null;
 76                 BufferedReader in = null;
 77                 
 78                 String sendString = "";
 79                 JSONObject json = JSONObject.fromObject(params);
 80                 System.out.println("发送报文:" + json.toString());
 81                 sendString = json.toString();
 82 
 83                 System.out.println("ERP连接:" + url);
 84                 System.out.println("发送给ERP信息:" + sendString);
 85                  
 86                  try {
 87                      trustAllHosts();
 88                     URL url2 = new URL(url);
 89                     
 90                     HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();
 91                     urlCon.setHostnameVerifier(DO_NOT_VERIFY);
 92                     urlCon.setDoOutput(true);
 93                     urlCon.setDoInput(true);
 94                     urlCon.setRequestMethod("POST");
 95                     urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");
 96                     // 发送POST请求必须设置如下两行
 97                     urlCon.setDoOutput(true);
 98                     urlCon.setDoInput(true);
 99                     // 获取URLConnection对象对应的输出流
100                     OutputStream os = urlCon.getOutputStream(); 
101                     //参数是键值队  , 不以"?"开始 
102                     os.write(sendString.getBytes()); 
103                     //os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes()); 
104                     os.flush();
105                     // 发送请求参数
106                     //out.print(a);
107                     // flush输出流的缓冲
108                     //out.flush();
109                     // 定义BufferedReader输入流来读取URL的响应
110                     in = new BufferedReader(
111 new InputStreamReader(urlCon.getInputStream()));
112                     String line;
113                     while ((line = in.readLine()) != null) {
114                         result += line;
115                     }
116                 } catch (Exception e) {
117                     e.printStackTrace();
118                 } finally {// 使用finally块来关闭输出流、输入流
119                     try {
120                         if (out != null) {
121                             out.close();
122                         }
123                         if (in != null) {
124                             in.close();
125                         }
126                     } catch (IOException ex) {
127                         ex.printStackTrace();
128                     }
129                 }
130                 return result;
131     }
132     
133 public static String http(String url, Map<String, String> reqMap) throws Exception {
134 
135         URL u = null;
136 
137         HttpURLConnection con = null;
138 
139         // 构建请求参数
140 
141         //StringBuffer sb = new StringBuffer();
142         String sendString = "" ;
143         //String tradeCode = params.get(ParamsConfig.keyTradeCode);
144         JSONObject json = JSONObject.fromObject(reqMap);
145         System.out.println("发送报文:"+json.toString());
146         sendString = json.toString();
147         /*if(tradeCode.equals(TradeCode.TRANS_WXAPP_PAY) || tradeCode.equals(TradeCode.TRANS_APP_QUERY)
148                 || tradeCode.equals(TradeCode.TRANS_TYPE_COLLECT) || tradeCode.equals(TradeCode.TRANS_TYPE_QUERY_COLLECT_TXN)){
149             JSONObject json = JSONObject.fromObject(params);
150             System.out.println("发送报文:"+json.toString());
151             sendString = json.toString();
152         } else {
153             if (params != null) {
154     
155                 for (Entry<String, String> e : params.entrySet()) {
156     
157                     sb.append(e.getKey());
158     
159                     sb.append("=");
160     
161                     sb.append(e.getValue());
162                     
163                     sb.append("&");
164     
165                 }
166                 sendString = sb.substring(0, sb.length() - 1);
167             }
168         }*/
169         System.out.println("ERP连接:" + url);
170         System.out.println("发送给ERP信息:" + sendString);
171 //        logger.info("ERP连接:" + url);
172 //        logger.info("发送给ERP信息:" + sb.toString());
173 
174         // 尝试发送请求
175 
176         try {
177 
178             u = new URL(url);
179 
180             con = (HttpURLConnection) u.openConnection();
181 
182             con.setRequestMethod("POST");
183 
184             con.setDoOutput(true);
185 
186             con.setDoInput(true);
187 
188             con.setUseCaches(false);
189             
190 //            con.setConnectTimeout(300*1000);
191 //            
192 //            con.setReadTimeout(300*1000);
193             
194             con.setRequestProperty("Content-Type",
195                     "application/x-www-form-urlencoded");
196 
197             OutputStreamWriter osw = new OutputStreamWriter(con
198                     .getOutputStream(), "UTF-8");
199 
200             osw.write(sendString);
201 
202             osw.flush();
203 
204             osw.close();
205 
206         } catch (Exception e) {
207             e.printStackTrace();
208             throw new Exception("与服务器连接发生错误:"+e.getMessage());
209 
210         } finally {
211 
212             if (con != null) {
213 
214                 con.disconnect();
215 
216             }
217 
218         }
219 
220         // 读取返回内容
221 
222         StringBuffer buffer = new StringBuffer();
223 
224         try {
225 
226             BufferedReader br = new BufferedReader(new InputStreamReader(con
227 
228             .getInputStream(), "UTF-8"));
229 
230             String temp;
231 
232             while ((temp = br.readLine()) != null) {
233 
234                 buffer.append(temp);
235             }
236 
237         } catch (Exception e) {
238             e.printStackTrace();
239             throw new Exception("从服务器获取数据失败:"+e.getMessage());
240 
241         }
242         
243         return buffer.toString();
244 
245     }
246 
247     
248 
249 }

 

Java的post(HTTPS)请求-----接口测试

标签:amp   错误   rand   key   context   OLE   buffere   必须   use   

原文地址:https://www.cnblogs.com/wangxiaoqun/p/9054746.html

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