[Java] Java处理HTTP请求的相关代码 →→→→→进入此内容的聊天室

来自 , 2020-12-26, 写在 Java, 查看 135 次.
URL http://www.code666.cn/view/e0384530
  1. package com.http.tool;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.regex.Pattern;
  9. /**
  10.  * Http操作辅助工具
  11.  *
  12.  * Get和Post两者在传递参数方式上有差异
  13.  *
  14.  * 1、Get: 把参数附加到url上,比如URL="http://www.abc.com?name=123&age=18"
  15.  * 2、Post:请求的url不变,但在content中加入参数,如 content="name=123&age=18",然后把content加入到post中
  16.  *
  17.  */
  18. public class HttpTool {
  19.      
  20.     /**
  21.      * GET请求数据
  22.      * @param get_url url地址
  23.      * @param content  key=value形式
  24.      * @return 返回结果
  25.      * @throws Exception
  26.      */
  27.     public String sendGetData(String get_url, String content) throws Exception {
  28.         String result = "";
  29.         URL getUrl = null;
  30.         BufferedReader reader = null;
  31.         String lines = "";
  32.         HttpURLConnection connection = null;
  33.         try {
  34.             if (content != null && !content.equals(""))
  35.                 get_url = get_url + "?" + content;
  36.                 //get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
  37.             getUrl = new URL(get_url);
  38.             connection = (HttpURLConnection) getUrl.openConnection();
  39.             connection.connect();
  40.             // 取得输入流,并使用Reader读取
  41.             reader = new BufferedReader(new InputStreamReader(connection
  42.                     .getInputStream(), "utf-8"));// 设置编码
  43.             while ((lines = reader.readLine()) != null) {
  44.                 result = result + lines;
  45.             }
  46.             return result;
  47.         } catch (Exception e) {
  48.             throw e;
  49.         } finally {
  50.             if (reader != null) {
  51.                 reader.close();
  52.                 reader = null;
  53.             }
  54.             connection.disconnect();
  55.         }
  56.     }
  57.      
  58.     /**
  59.      * @param POST_URL url地址
  60.      * @param content  key=value形式
  61.      * @return 返回结果
  62.      * @throws Exception
  63.      */
  64.     public String sendPostData(String POST_URL, String content)
  65.             throws Exception {
  66.         HttpURLConnection connection=null;
  67.         DataOutputStream out=null;
  68.         BufferedReader reader=null;
  69.         String line = "";
  70.         String result="";
  71.         try {
  72.             URL postUrl = new URL(POST_URL);
  73.             connection= (HttpURLConnection) postUrl.openConnection();
  74.             connection.setDoOutput(true);//Let the run-time system (RTS) know that we want input
  75.             connection.setDoInput(true);//we want to do output.
  76.             connection.setRequestMethod("POST");            
  77.             connection.setUseCaches(false);// Post 请求不能使用缓存
  78.             connection.setInstanceFollowRedirects(true);
  79.             connection.setRequestProperty("Content-Type",//Specify the header content type.
  80.                     "application/x-www-form-urlencoded");
  81.             connection.connect();
  82.              
  83.             out = new DataOutputStream(connection.getOutputStream()); // Send POST output.
  84.              
  85.             // DataOutputStream.writeBytes将字符串中的16位的unicode字符变为utf-8的字符形式写道流里
  86.             //content = URLEncoder.encode(content, "utf-8");
  87.              
  88.             out.writeBytes(content);
  89.              
  90.             /**
  91.              * 如果url中带有多个key-value参数对,则采用下面的方式写到content中
  92.              * 正文内容其实跟get的URL中'?'后的参数字符串一致
  93.              *
  94.             String content =
  95.                 "name=" + URLEncoder.encode ("Hitesh Agrawal") +
  96.                 "&profession=" + URLEncoder.encode ("Software Engineer");
  97.             out.flush();
  98.             out.close(); */
  99.              
  100.             //获取结果
  101.             reader = new BufferedReader(new InputStreamReader(
  102.                     connection.getInputStream(), "utf-8"));// 设置编码
  103.             while ((line = reader.readLine()) != null) {
  104.                 result=result+line;
  105.             }        
  106.             return result;
  107.         } catch (Exception e) {
  108.             throw e;
  109.         }finally
  110.         {
  111.             if(out!=null)
  112.             {
  113.                 out.close();
  114.                 out=null;                
  115.             }
  116.             if(reader!=null)
  117.             {
  118.                 reader.close();
  119.                 reader=null;                
  120.             }
  121.             connection.disconnect();
  122.         }
  123.     }
  124.    
  125.     /*
  126.      * 过滤掉html里不安全的标签,不允许用户输入这些符号
  127.      */
  128.     public static String htmlFilter(String inputString) {
  129.         //return inputString;
  130.           String htmlStr = inputString; // 含html标签的字符串
  131.           String textStr = "";
  132.           java.util.regex.Pattern p_script;
  133.           java.util.regex.Matcher m_script;
  134.              
  135.          
  136.           try {
  137.            String regEx_script = "<[s]*?(script|style)[^>]*?>[sS]*?<[s]*?/[s]*?(script|style)[s]*?>";
  138.            String regEx_onevent="on[^s]+=s*";
  139.            String regEx_hrefjs="href=javascript:";
  140.            String regEx_iframe="<[s]*?(iframe|frameset)[^>]*?>[sS]*?<[s]*?/[s]*?(iframe|frameset)[s]*?>";
  141.            String regEx_link="<[s]*?link[^>]*?/>";
  142.            
  143.            htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
  144.            htmlStr=Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
  145.            htmlStr=Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
  146.            htmlStr=Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
  147.            htmlStr=Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
  148.            
  149.            //p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
  150.           // m_html = p_html.matcher(htmlStr);
  151.           // htmlStr = m_html.replaceAll(""); // 过滤html标签
  152.  
  153.            textStr = htmlStr;
  154.  
  155.           } catch (Exception e) {
  156.            System.err.println("Html2Text: " + e.getMessage());
  157.           }
  158.  
  159.           return textStr;
  160.         }
  161.  
  162.     public static void main(String[] args){
  163.         HttpTool ht = new HttpTool();
  164.         try {
  165.             ht.sendGetData("http://www.baidu.com", "");
  166.         } catch (Exception e) {
  167.             // TODO Auto-generated catch block
  168.             e.printStackTrace();
  169.         }
  170.     }
  171. }
  172. //java/6824

回复 "Java处理HTTP请求的相关代码"

这儿你可以回复上面这条便签

captcha