欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HTTP 请求 的方法Util

程序员文章站 2022-07-01 23:36:51
HTTP请求 的一系列方法总结 ......

http请求 的一系列方法总结


 

  1  /**
  2         * *******************************传统请求--开始**************************************
  3         * */
  4     
  5     /**
  6      * httpclient 发送 post 请求
  7      * @param url  路径:string
  8      * @param mapparam 参数:java.util.map
  9      * @return
 10      */
 11     public static string sendclientpost(string url,map<string,string> headers,map<string,string> mapparam){
 12         return httppost(url, headers,new jsonobject(mapparam), false);
 13     }
 14     
 15     /**
 16      * httpclient 发送 post 请求
 17      * @param url  路径:string
 18      * @param jsonobjectparam 参数:org.json.jsonobject
 19      * @return
 20      */
 21     public static string sendclientpost(string url,map<string,string> headers,jsonobject jsonobjectparam){
 22         return httppost(url, headers,jsonobjectparam, false);
 23     }
 24     
 25     
 26     /**
 27      * httpclient 发送 get 请求
 28      * @param url 路径:string
 29      * @return
 30      */
 31     public static string sendclientget(string url){
 32         return httpget(url,null);
 33     }
 34     /**
 35      * httpclient 发送 get 请求
 36      * @param url 路径:string
 37      * @param headers map<string,string>
 38      * @return
 39      */
 40     public static string sendclientget(string url,map<string,string> headers){
 41         return httpget(url,headers);
 42     }
 43     
 44     /**
 45      * httpclient 发送 delete 请求
 46      * @param url 路径:string
 47      * @return
 48      */
 49     public static string sendclientdelete(string url){
 50         return httpdelete(url,null);
 51     }
 52     /**
 53      * httpclient 发送 delete 请求
 54      * @param url 路径:string
 55      * @param headers map<string,string>
 56      * @return
 57      */
 58     public static string sendclientdelete(string url,map<string,string> headers){
 59         return httpdelete(url,headers);
 60     }
 61     
 62     
 63     /**
 64      * urlconnectionget
 65      * @param url  路径
 66      * @return
 67      */
 68     public static string sendconnectionget(string url,string param){
 69         return sendget(url,param);
 70     } 
 71     
 72     /**
 73      * 向指定 url 发送post方法的请求
 74      * @param url 发送请求的 url
 75      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 76      * @return 所代表远程资源的响应结果
 77      */
 78     public static string sendconnectionpost(string url,string param){
 79         return sendpost(url,param);
 80     }
 81     /**
 82         * *******************************传统请求--结束**************************************
 83         * */
 84     
 85  
 86     /**
 87         * *******************************jsoup请求--开始**************************************
 88         * */
 89     
 90        /**
 91         * 发送 post 请求
 92         * @param url 请求地址
 93         * @param cookie cookie:string
 94         * @param headers 头信息:map<string,string>
 95         * @param params 参数:map<string,object>
 96         * @return string
 97         */
 98        public static string sendjsouppost(string url,string cookie,map<string,string> headers,map<string,object> params,boolean isjsonparam) {
 99            string sendrequest = sendrequest(url, cookie, headers,params, "post",isjsonparam);
100            return sendrequest;
101        }
102        
103        /**
104         * 发送 post 请求
105         * @param url 请求地址
106         * @param headers 头信息:map<string,string>
107         * @param params 参数:map<string,object>
108         * @return string
109         */
110        public static string sendjsouppost(string url,map<string,string> headers,map<string,object> params,boolean isjsonparam) {
111            string sendrequest = sendrequest(url, null, headers,params, "post", isjsonparam);
112            return sendrequest;
113        }
114        
115        /**
116         * 发送 post 请求
117         * @param url 请求地址
118         * @param cookie cookie:string
119         * @param headers 头信息:map<string,string>
120         * @param params 参数:map<string,object>
121         * @return string
122         */
123        public static string sendjsouppost(string url,map<string,object> params,boolean isjsonparam) {
124            string sendrequest = sendrequest(url, null, null,params, "post", isjsonparam);
125            return sendrequest;
126        }
127        
128        
129        /**
130         * 发送 post 请求
131         * @param url 请求地址
132         * @return string
133         */
134        public static string sendjsouppost(string url) {
135            string sendrequest = sendrequest(url,  null, null,null, "post",false);
136            return sendrequest;
137        }
138        
139        
140        /**
141         * 发送 get 请求
142         * @param url 请求地址: string
143         * @param cookie cookie:string
144         * @param headers 头信息:map<string,string>
145         * @param params 参数:map<string,object>
146         * @return string
147         */
148        public static string sendjsoupget(string url,string cookie,map<string,string> headers,map<string,object> params) {
149            string sendrequest = sendrequest(url, cookie, headers,params, "get",false);
150            return sendrequest;
151        }
152        
153        /**
154         * 发送 get 请求
155         * @param url 请求地址: string
156         * @param headers 头信息:map<string,string>
157         * @param params 参数:map<string,object>
158         * @return string
159         */
160        public static string sendjsoupget(string url,map<string,string> headers,map<string,object> params) {
161            string sendrequest = sendrequest(url, null, headers,params, "get",false);
162            return sendrequest;
163        }
164        
165        /**
166         * 发送 get 请求
167         * @param url 请求地址: string
168         * @return string
169         */
170        public static string sendjsoupget(string url) {
171            string sendrequest = sendrequest(url, null, null,null, "get",false);
172            return sendrequest;
173        }
174        
175        /**
176         * 发送 get 请求
177         * @param url 请求地址: string
178         * @param params 参数:map<string,object>
179         * @return string
180         */
181        public static string sendjsoupget(string url,map<string,object> params) {
182            string sendrequest = sendrequest(url, null, null,params, "get",false);
183            return sendrequest;
184        }
185        
186     /**
187         * *******************************jsoup请求--结束**************************************
188         * */
189        
190        
191        /**
192         * *******************************获取网页对象--开始**************************************
193         * */
194        
195        /**
196         * 发送 get 请求
197         * @param url 请求地址: string
198         * @return document
199         */
200        public static document sendjsoupgetdocument(string url) {
201            document sendrequestdocument = sendrequestdocument(url, null, null,null, "get",false);
202            return sendrequestdocument;
203        }
204        
205        /**
206         * 发送 get 请求
207         * @param url 请求地址: string
208         * @param cookie cookie:string
209         * @param headers 头信息:map<string,string>
210         * @param params 参数:map<string,object>
211         * @return document
212         */
213        public static document sendjsoupgetdocument(string url,string cookie,map<string,string> headers,map<string,object> params) {
214            document sendrequest = sendrequestdocument(url, cookie, headers,params, "get",false);
215            return sendrequest;
216        }
217        
218        /**
219         * 发送 post 请求
220         * @param url 请求地址: string
221         * @return document
222         */
223        public static document sendjsouppostdocument(string url) {
224            document sendrequestdocument = sendrequestdocument(url, null, null,null, "post",false);
225            return sendrequestdocument;
226        }
227        
228        /**
229         * 发送 post 请求
230         * @param url 请求地址
231         * @param cookie cookie:string
232         * @param headers 头信息:map<string,string>
233         * @param params 参数:map<string,object>
234         * @return document
235         */
236        public static document sendjsouppostdocument(string url,string cookie,map<string,string> headers,map<string,object> params,boolean isjsonparam) {
237            document sendrequest = sendrequestdocument(url, cookie, headers,params, "post", isjsonparam);
238            return sendrequest;
239        }
240        
241        
242     /**
243         * *******************************获取网页对象--结束**************************************
244         * */
245        
246     
247     
248     
249     
250     
251     
252     /**
253      * post请求
254      * @param url         url地址
255      * @param jsonparam     参数
256      * @param noneedresponse    不需要返回结果
257      * @return
258      */
259     private static string httppost(string url,map<string,string> headers,jsonobject jsonparam, boolean noneedresponse){
260         //post请求返回结果
261         closeablehttpclient httpclient = httpclients.createdefault();
262 //        defaulthttpclient httpclient = new defaulthttpclient();
263         string jsonresult = null;
264         httppost method = new httppost(url);
265         
266         if(headers!=null){
267             set<string> keyset = headers.keyset();
268             for (string key : keyset) {
269                 method.addheader(key, headers.get(key));
270             }
271         }
272         try {
273             if (null != jsonparam) {
274                 //解决中文乱码问题
275                 stringentity entity = new stringentity(jsonparam.tostring(), "utf-8");
276                 entity.setcontentencoding("utf-8");
277                 entity.setcontenttype("application/json");
278                 method.setentity(entity);
279             }
280             httpresponse result = httpclient.execute(method);
281             url = urldecoder.decode(url, "utf-8");
282             /**请求发送成功,并得到响应**/
283             //if (result.getstatusline().getstatuscode() == 200) {
284                 try {
285                     /**读取服务器返回过来的json字符串数据**/
286                     jsonresult = entityutils.tostring(result.getentity());
287                     if (noneedresponse) {
288                         return null;
289                     }
290                     /**把json字符串转换成json对象**/
291                 } catch (exception e) {
292                     logger.error("httppost请求提交失败:" + url, e);
293                 }
294             //}
295         } catch (exception e) {
296             logger.error("httppost请求提交失败:" + url, e);
297         }
298         return jsonresult;
299     }
300  
301  
302     /**
303      * 发送get请求
304      * @param url    路径
305      * @return
306      */
307     private static string httpget(string url,map<string,string> headers){
308         //get请求返回结果
309         string jsonresult = null;
310         try {
311             closeablehttpclient httpclient = httpclients.createdefault();
312 //            defaulthttpclient client = new defaulthttpclient();
313             //发送get请求
314             httpget request = new httpget(url);
315             if(headers!=null){
316                 set<string> keyset = headers.keyset();
317                 for (string key : keyset) {
318                     request.addheader(key, headers.get(key));
319                 }
320             }
321             
322             httpresponse response = httpclient.execute(request);
323  
324             /**请求发送成功,并得到响应**/
325             if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) {
326                 /**读取服务器返回过来的json字符串数据**/
327                 jsonresult = entityutils.tostring(response.getentity());
328             } else {
329                 logger.error("httpget请求提交失败:" + url);
330             }
331         } catch (exception e) {
332             logger.error("httpget请求提交失败:" + url, e);
333         }
334         return jsonresult;
335     }
336     
337     /**
338      * 发送get请求
339      * @param url 路径
340      * @return
341      */
342     private static string httpdelete(string url,map<string,string> headers){
343         //get请求返回结果
344         string jsonresult = null;
345         try {
346             closeablehttpclient httpclient = httpclients.createdefault();
347 //            defaulthttpclient client = new defaulthttpclient();
348             //发送get请求
349             httpdelete request = new httpdelete(url);
350             if(headers!=null){
351                 set<string> keyset = headers.keyset();
352                 for (string key : keyset) {
353                     request.addheader(key, headers.get(key));
354                 }
355             }
356             
357             httpresponse response = httpclient.execute(request);
358             
359             /**请求发送成功,并得到响应**/
360             if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) {
361                 /**读取服务器返回过来的json字符串数据**/
362                 jsonresult = entityutils.tostring(response.getentity());
363             } else {
364                 logger.error("httpdelete请求提交失败:" + url);
365             }
366         } catch (exception e) {
367             logger.error("httpdelete请求提交失败:" + url, e);
368         }
369         return jsonresult;
370     }
371     
372     /**
373      * 向指定url发送get方法的请求
374      * @param url 发送请求的url
375      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
376      * @return url 所代表远程资源的响应结果
377      */
378     private static string sendget(string url, string param) {
379         
380         string result = "";
381         bufferedreader in = null;
382         try {
383             string urlnamestring = url + "?" + param;
384             url realurl = new url(urlnamestring);
385             // 打开和url之间的连接
386             urlconnection connection = realurl.openconnection();
387             // 设置通用的请求属性
388             connection.setrequestproperty("accept", "*/*");
389             connection.setrequestproperty("connection", "keep-alive");
390             connection.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
391             // 建立实际的连接
392             connection.connect();
393             // 获取所有响应头字段
394             // map<string, list<string>> map = connection.getheaderfields();
395             // 遍历所有的响应头字段
396             // 定义 bufferedreader输入流来读取url的响应
397             in = new bufferedreader(new inputstreamreader(connection.getinputstream(),"utf-8"));
398             string line;
399             while ((line = in.readline()) != null) {
400                 result += line;
401             }
402         } catch (exception e) {
403             system.out.println("发送get请求出现异常!" + e);
404             e.printstacktrace();
405         }
406         // 使用finally块来关闭输入流
407         finally {
408             try {
409                 if (in != null) {
410                     in.close();
411                 }
412             } catch (exception e2) {
413                 e2.printstacktrace();
414             }
415         }
416         return result;
417     }
418     
419 
420     /**
421      * 向指定 url 发送post方法的请求
422      * @param url 发送请求的 url
423      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
424      * @return 所代表远程资源的响应结果
425      */
426     private static string sendpost(string url, string param) {
427         
428         printwriter out = null;
429         bufferedreader in = null;
430         string result = "";
431         try {
432             url realurl = new url(url);
433             // 打开和url之间的连接
434             urlconnection conn = realurl.openconnection();
435             // 设置通用的请求属性
436             conn.setrequestproperty("accept", "*/*");
437             conn.setrequestproperty("connection", "keep-alive");
438             conn.setrequestproperty("user-agent","mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
439             // 发送post请求必须设置如下两行
440             conn.setdooutput(true);
441             conn.setdoinput(true);
442             // 获取urlconnection对象对应的输出流
443             out = new printwriter(conn.getoutputstream());
444             // 发送请求参数
445             out.print(param);
446             // flush输出流的缓冲
447             out.flush();
448             // 定义bufferedreader输入流来读取url的响应
449             in = new bufferedreader(new inputstreamreader(conn.getinputstream()));
450             string line;
451             while ((line = in.readline()) != null) {
452                 result += line;
453             }
454         } catch (exception e) {
455             system.out.println("发送 post 请求出现异常!"+e);
456             e.printstacktrace();
457         }finally{
458             try{
459                 if(out!=null){
460                     out.close();
461                 }
462                 if(in!=null){
463                     in.close();
464                 }
465             }catch(exception ex){
466                 ex.printstacktrace();
467             }
468         }
469         return result;
470     }
471    
472     /** 发送 利用jsoup 发送 request 请求
473      * @param url 请求地址: string
474      * @param cookie cookie:string
475      * @param headers 头信息:map<string,string>
476      * @param params 参数:map<string,object>
477      * @param method 请求方式: string,ger or post
478      * @return string
479      */
480     private static string sendrequest(string url,string cookie,map<string,string> headers,map<string,object> params,string method,boolean isjsonparam) {
481         string res = null;
482         try {
483             document document = null;
484             connection connect = getconnection(url, cookie, headers, params,isjsonparam);
485             connect.ignorecontenttype(true);
486             if("get".equals(method)) {
487                 document = connect.get();
488             }else if("post".equals(method)) {
489                 document = connect.post();
490             }
491             
492             if(document != null) {
493                 res = document.body().text();
494             }
495         } catch (exception e) {
496             e.printstacktrace();
497         }
498         return res;
499     }
500     
501     
502     /** 发送 利用jsoup 发送 request 请求
503      * @param url 请求地址: string
504      * @param cookie cookie:string
505      * @param headers 头信息:map<string,string>
506      * @param params 参数:map<string,object>
507      * @param method 请求方式: string,ger or post
508      * @return string
509      */
510     private static document sendrequestdocument(string url,string cookie,map<string,string> headers,map<string,object> params,string method,boolean isjsonparam) {
511         document document = null;
512         try {
513             connection connect = getconnection(url, cookie, headers, params,isjsonparam);
514             connect.ignorecontenttype(true);
515             if("get".equals(method)) {
516                 document = connect.get();
517             }else if("post".equals(method)) {
518                 document = connect.post();
519             }
520         } catch (exception e) {
521             e.printstacktrace();
522         }
523         return document;
524     }
525     
526     /** 
527      * 获取jsoup connection
528      * @param url 请求地址: string
529      * @param cookie cookie:string
530      * @param headers 头信息:map<string,string>
531      * @param params 头信息:map<string,object>
532      * @return connection org.jsoup.connection
533      */
534     private static connection getconnection(string url,string cookie,map<string,string> headers,map<string,object> params,boolean isjsonparam) {
535         connection connect = jsoup.connect(url);
536         if(cookie != null) {
537             connect.header("cookie", cookie);
538         }
539         
540         if(params != null) {
541             map<string,string> param = new hashmap<string,string>();
542             set<string> keyset = params.keyset();
543             for (string key : keyset) {
544                 if(params.get(key) != null){
545                     param.put(key, params.get(key)==null ? null : params.get(key)+"");
546                 }
547             }
548             if(isjsonparam){
549                 connect.requestbody(new jsonobject(param).tostring());
550 //                connect.postdatacharset(new jsonobject(param).tostring());
551             }else{
552                 
553                 connect.data(param);
554             }
555         }
556         
557         if(headers!= null) {
558             connect.headers(headers);
559         }else if(headers==null) {
560             connect.header("accept", "application/json");
561             connect.header("user-agent", "mozilla/5.0 (windows nt 10.0; win64; x64; rv:58.0) gecko/20100101 firefox/58.0");
562         }
563         return connect;
564     }
565