Java處理HTTP請求的相關代碼

dw23 9年前發布 | 2K 次閱讀 Java

可以用于處理HTTP GET請求,POST請求,過濾HTML代碼等

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
/**

  • Http操作輔助工具 *
  • Get和Post兩者在傳遞參數方式上有差異 *
  • 1、Get: 把參數附加到url上,比如URL="http://www.abc.com?name=123&age=18"
  • 2、Post:請求的url不變,但在content中加入參數,如 content="name=123&age=18",然后把content加入到post中 / public class HttpTool {

    /**

    • GET請求數據
    • @param get_url url地址
    • @param content key=value形式
    • @return 返回結果
    • @throws Exception */ public String sendGetData(String get_url, String content) throws Exception { String result = ""; URL getUrl = null; BufferedReader reader = null; String lines = ""; HttpURLConnection connection = null; try {

       if (content != null && !content.equals(""))
           get_url = get_url + "?" + content;
           //get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
       getUrl = new URL(get_url);
       connection = (HttpURLConnection) getUrl.openConnection();
       connection.connect();
       // 取得輸入流,并使用Reader讀取
       reader = new BufferedReader(new InputStreamReader(connection
               .getInputStream(), "utf-8"));// 設置編碼
       while ((lines = reader.readLine()) != null) {
           result = result + lines;
       }
       return result;
      

      } catch (Exception e) {

       throw e;
      

      } finally {

       if (reader != null) {
           reader.close();
           reader = null;
       }
       connection.disconnect();
      

      } }

      /**

    • @param POST_URL url地址
    • @param content key=value形式
    • @return 返回結果
    • @throws Exception */ public String sendPostData(String POST_URL, String content)

       throws Exception {
      

      HttpURLConnection connection=null; DataOutputStream out=null; BufferedReader reader=null; String line = ""; String result=""; try {

       URL postUrl = new URL(POST_URL);
       connection= (HttpURLConnection) postUrl.openConnection();
       connection.setDoOutput(true);//Let the run-time system (RTS) know that we want input
       connection.setDoInput(true);//we want to do output.
       connection.setRequestMethod("POST");           
       connection.setUseCaches(false);// Post 請求不能使用緩存
       connection.setInstanceFollowRedirects(true);
       connection.setRequestProperty("Content-Type",//Specify the header content type.
               "application/x-www-form-urlencoded");
       connection.connect();
      
       out = new DataOutputStream(connection.getOutputStream()); // Send POST output.
      
       // DataOutputStream.writeBytes將字符串中的16位的unicode字符變為utf-8的字符形式寫道流里
       //content = URLEncoder.encode(content, "utf-8");
      
       out.writeBytes(content);
      
       /**
        * 如果url中帶有多個key-value參數對,則采用下面的方式寫到content中
        * 正文內容其實跟get的URL中'?'后的參數字符串一致
        *
       String content =
           "name=" + URLEncoder.encode ("Hitesh Agrawal") +
           "&profession=" + URLEncoder.encode ("Software Engineer");
       out.flush();
       out.close(); */
      
       //獲取結果
       reader = new BufferedReader(new InputStreamReader(
               connection.getInputStream(), "utf-8"));// 設置編碼
       while ((line = reader.readLine()) != null) {
           result=result+line;
       }       
       return result;
      

      } catch (Exception e) {

       throw e;
      

      }finally {

       if(out!=null)
       {
           out.close();
           out=null;               
       }
       if(reader!=null)
       {
           reader.close();
           reader=null;               
       }
       connection.disconnect();
      

      } }

      /*

    • 過濾掉html里不安全的標簽,不允許用戶輸入這些符號 */ public static String htmlFilter(String inputString) { //return inputString; String htmlStr = inputString; // 含html標簽的字符串 String textStr = ""; java.util.regex.Pattern p_script; java.util.regex.Matcher m_script;
      try {
       String regEx_script = "<[s]*?(script|style)[^>]*?>[sS]*?<[s]*?/[s]*?(script|style)[s]*?>";
       String regEx_onevent="on[^s]+=s*";
       String regEx_hrefjs="href=javascript:";
       String regEx_iframe="<[s]*?(iframe|frameset)[^>]*?>[sS]*?<[s]*?/[s]*?(iframe|frameset)[s]*?>";
       String regEx_link="<[s]*?link[^>]*?/>";

       htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
       htmlStr=Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
       htmlStr=Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
       htmlStr=Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
       htmlStr=Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");

       //p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
      // m_html = p_html.matcher(htmlStr);
      // htmlStr = m_html.replaceAll(""); // 過濾html標簽

       textStr = htmlStr;

      } catch (Exception e) {
       System.err.println("Html2Text: " + e.getMessage());
      }

      return textStr;
    }

public static void main(String[] args){
    HttpTool ht = new HttpTool();
    try {
        ht.sendGetData("http://www.baidu.com", "");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}</pre>

 本文由用戶 dw23 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!