纯 java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包

来源:互联网 发布:图灵奖难度 知乎 编辑:程序博客网 时间:2024/04/28 22:43
原文:纯 java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包
源代码下载地址:http://www.zuidaima.com/share/1550463379950592.htm

纯 java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包

纯 Java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包

1. 抓取指定 URL 的资源,可以作为流,也可以作为 String

2. 向指定 URL POST 数据,模拟表单提交。

例如:你想模拟 XXX 自动登陆,然后再发表心情、签名之类的

3. 支持 URL 重定向

[java] view plain copy
print?
  1. /* 
  2.  *    Copyright 2012-2013 The Haohui Network Corporation 
  3.  */  
  4. package com.haohui.common.utils;  
  5.   
  6. /** 
  7.  * @file HttpUtil.java 
  8.  *  
  9.  * @brief  
  10.  * HttpUtil is a single class containing methods to conveniently perform HTTP  
  11.  * requests. HttpUtil only uses regular java io and net functionality and does  
  12.  * not depend on external libraries.  
  13.  * The class contains methods to perform a get, post, put, and delete request, 
  14.  * and supports posting forms. Optionally, one can provide headers. 
  15.  * 
  16.  * Example usage: 
  17.  *  
  18.  *     // get 
  19.  *     String res = HttpUtil.get("http://www.zuidaima.com"); 
  20.  *  
  21.  *     // post 
  22.  *     String res = HttpUtil.post("http://www.zuidaima.com/share/1550463379950592.htm", "This is the data"); 
  23.  * 
  24.  *     // post form 
  25.  *     Map<String, String> params = new HashMap<String, String>(); 
  26.  *     params.put("firstname", "Joe"); 
  27.  *     params.put("lastname", "Smith"); 
  28.  *     params.put("age", "28"); 
  29.  *     String res = HttpUtil.postForm("http://site.com/newuser", params); 
  30.  * 
  31.  *     // append query parameters to url 
  32.  *     String url = "http://mydatabase.com/users"; 
  33.  *     Map<String, String> params = new HashMap<String, String>(); 
  34.  *     params.put("orderby", "name"); 
  35.  *     params.put("limit", "10"); 
  36.  *     String fullUrl = HttpUtil.appendQueryParams(url, params); 
  37.  *     // fullUrl = "http://mydatabase.com/user?orderby=name&limit=10" 
  38.  * 
  39.  * @license 
  40.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
  41.  * use this file except in compliance with the License. You may obtain a copy  
  42.  * of the License at 
  43.  *  
  44.  * http://www.apache.org/licenses/LICENSE-2.0 
  45.  *  
  46.  * Unless required by applicable law or agreed to in writing, software 
  47.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  48.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  49.  * License for the specific language governing permissions and limitations under 
  50.  * the License. 
  51.  * 
  52.  * Copyright (c) 2012 Almende B.V. 
  53.  * 
  54.  * @author  Jos de Jong, <jos@almende.org> www.zuidaima.com 
  55.  * @date      2012-05-14 
  56.  */  
  57.   
  58. import java.io.IOException;  
  59. import java.io.InputStream;  
  60. import java.io.OutputStream;  
  61. import java.net.HttpURLConnection;  
  62. import java.net.URL;  
  63. import java.net.URLDecoder;  
  64. import java.net.URLEncoder;  
  65. import java.util.HashMap;  
  66. import java.util.Map;  
  67.   
  68. /** 
  69.  * https://raw.github.com/wjosdejong/httputil/master/src/com/almende/util/HttpUtil.java 
  70.  *  
  71.  * @project baidamei 
  72.  * @author cevencheng <cevencheng@gmail.com> 
  73.  * @create 2012-11-17 下午2:35:38 
  74.  */  
  75. public class HttpUtil {  
  76.     /** 
  77.      * Send a get request 
  78.      * @param url 
  79.      * @return response 
  80.      * @throws IOException  
  81.      */  
  82.     static public String get(String url) throws IOException {  
  83.         return get(url, null);  
  84.     }  
  85.   
  86.     /** 
  87.      * Send a get request 
  88.      * @param url         Url as string 
  89.      * @param headers     Optional map with headers 
  90.      * @return response   Response as string 
  91.      * @throws IOException  
  92.      */  
  93.     static public String get(String url,  
  94.             Map<String, String> headers) throws IOException {  
  95.         return fetch("GET", url, null, headers);  
  96.     }  
  97.   
  98.     /** 
  99.      * Send a post request 
  100.      * @param url         Url as string 
  101.      * @param body        Request body as string 
  102.      * @param headers     Optional map with headers 
  103.      * @return response   Response as string 
  104.      * @throws IOException  
  105.      */  
  106.     static public String post(String url, String body,  
  107.             Map<String, String> headers) throws IOException {  
  108.         return fetch("POST", url, body, headers);  
  109.     }  
  110.   
  111.     /** 
  112.      * Send a post request 
  113.      * @param url         Url as string 
  114.      * @param body        Request body as string 
  115.      * @return response   Response as string 
  116.      * @throws IOException  
  117.      */  
  118.     static public String post(String url, String body) throws IOException {  
  119.         return post(url, body, null);  
  120.     }  
  121.   
  122.     /** 
  123.      * Post a form with parameters 
  124.      * @param url         Url as string 
  125.      * @param params      map with parameters/values 
  126.      * @return response   Response as string 
  127.      * @throws IOException  
  128.      */  
  129.     static public String postForm(String url, Map<String, String> params)   
  130.             throws IOException {  
  131.         return postForm(url, params, null);  
  132.     }  
  133.   
  134.     /** 
  135.      * Post a form with parameters 
  136.      * @param url         Url as string 
  137.      * @param params      Map with parameters/values 
  138.      * @param headers     Optional map with headers 
  139.      * @return response   Response as string 
  140.      * @throws IOException  
  141.      */  
  142.     static public String postForm(String url, Map<String, String> params,  
  143.             Map<String, String> headers) throws IOException {  
  144.         // set content type  
  145.         if (headers == null) {  
  146.             headers = new HashMap<String, String>();  
  147.         }  
  148.         headers.put("Content-Type""application/x-www-form-urlencoded");  
  149.   
  150.         // parse parameters  
  151.         String body = "";  
  152.         if (params != null) {  
  153.             boolean first = true;  
  154.             for (String param : params.keySet()) {  
  155.                 if (first) {  
  156.                     first = false;  
  157.                 }  
  158.                 else {  
  159.                     body += "&";  
  160.                 }  
  161.                 String value = params.get(param);  
  162.                 body += URLEncoder.encode(param, "UTF-8") + "=";  
  163.                 body += URLEncoder.encode(value, "UTF-8");  
  164.             }  
  165.         }  
  166.   
  167.         return post(url, body, headers);  
  168.     }  
  169.   
  170.     /** 
  171.      * Send a put request 
  172.      * @param url         Url as string 
  173.      * @param body        Request body as string 
  174.      * @param headers     Optional map with headers 
  175.      * @return response   Response as string 
  176.      * @throws IOException  
  177.      */  
  178.     static public String put(String url, String body,  
  179.             Map<String, String> headers) throws IOException {  
  180.         return fetch("PUT", url, body, headers);  
  181.     }  
  182.   
  183.     /** 
  184.      * Send a put request 
  185.      * @param url         Url as string 
  186.      * @return response   Response as string 
  187.      * @throws IOException  
  188.      */  
  189.     static public String put(String url, String body) throws IOException {  
  190.         return put(url, body, null);  
  191.     }  
  192.       
  193.     /** 
  194.      * Send a delete request 
  195.      * @param url         Url as string 
  196.      * @param headers     Optional map with headers 
  197.      * @return response   Response as string 
  198.      * @throws IOException  
  199.      */  
  200.     static public String delete(String url,  
  201.             Map<String, String> headers) throws IOException {  
  202.         return fetch("DELETE", url, null, headers);  
  203.     }  
  204.       
  205.     /** 
  206.      * Send a delete request 
  207.      * @param url         Url as string 
  208.      * @return response   Response as string 
  209.      * @throws IOException  
  210.      */  
  211.     static public String delete(String url) throws IOException {  
  212.         return delete(url, null);  
  213.     }  
  214.       
  215.     /** 
  216.      * Append query parameters to given url 
  217.      * @param url         Url as string 
  218.      * @param params      Map with query parameters 
  219.      * @return url        Url with query parameters appended 
  220.      * @throws IOException  
  221.      */  
  222.     static public String appendQueryParams(String url,   
  223.             Map<String, String> params) throws IOException {  
  224.         String fullUrl = new String(url);  
  225.           
  226.         if (params != null) {  
  227.             boolean first = (fullUrl.indexOf('?') == -1);  
  228.             for (String param : params.keySet()) {  
  229.                 if (first) {  
  230.                     fullUrl += '?';  
  231.                     first = false;  
  232.                 }  
  233.                 else {  
  234.                     fullUrl += '&';  
  235.                 }  
  236.                 String value = params.get(param);  
  237.                 fullUrl += URLEncoder.encode(param, "UTF-8") + '=';  
  238.                 fullUrl += URLEncoder.encode(value, "UTF-8");  
  239.             }  
  240.         }  
  241.           
  242.         return fullUrl;  
  243.     }  
  244.       
  245.     /** 
  246.      * Retrieve the query parameters from given url 
  247.      * @param url         Url containing query parameters 
  248.      * @return params     Map with query parameters 
  249.      * @throws IOException  
  250.      */  
  251.     static public Map<String, String> getQueryParams(String url)   
  252.             throws IOException {  
  253.         Map<String, String> params = new HashMap<String, String>();  
  254.       
  255.         int start = url.indexOf('?');  
  256.         while (start != -1) {  
  257.             // read parameter name  
  258.             int equals = url.indexOf('=', start);  
  259.             String param = "";  
  260.             if (equals != -1) {  
  261.                 param = url.substring(start + 1, equals);  
  262.             }  
  263.             else {  
  264.                 param = url.substring(start + 1);  
  265.             }  
  266.               
  267.             // read parameter value  
  268.             String value = "";  
  269.             if (equals != -1) {  
  270.                 start = url.indexOf('&', equals);  
  271.                 if (start != -1) {  
  272.                     value = url.substring(equals + 1, start);  
  273.                 }  
  274.                 else {  
  275.                     value = url.substring(equals + 1);  
  276.                 }  
  277.             }  
  278.               
  279.             params.put(URLDecoder.decode(param, "UTF-8"),   
  280.                 URLDecoder.decode(value, "UTF-8"));  
  281.         }  
  282.           
  283.         return params;  
  284.     }  
  285.   
  286.     /** 
  287.      * Returns the url without query parameters 
  288.      * @param url         Url containing query parameters 
  289.      * @return url        Url without query parameters 
  290.      * @throws IOException  
  291.      */  
  292.     static public String removeQueryParams(String url)   
  293.             throws IOException {  
  294.         int q = url.indexOf('?');  
  295.         if (q != -1) {  
  296.             return url.substring(0, q);  
  297.         }  
  298.         else {  
  299.             return url;  
  300.         }  
  301.     }  
  302.       
  303.     /** 
  304.      * Send a request 
  305.      * @param method      HTTP method, for example "GET" or "POST" 
  306.      * @param url         Url as string 
  307.      * @param body        Request body as string 
  308.      * @param headers     Optional map with headers 
  309.      * @return response   Response as string 
  310.      * @throws IOException  
  311.      */  
  312.     static public String fetch(String method, String url, String body,  
  313.             Map<String, String> headers) throws IOException {  
  314.         // connection  
  315.         URL u = new URL(url);  
  316.         HttpURLConnection conn = (HttpURLConnection)u.openConnection();  
  317.         conn.setConnectTimeout(10000);  
  318.         conn.setReadTimeout(10000);  
  319.   
  320.         // method  
  321.         if (method != null) {  
  322.             conn.setRequestMethod(method);  
  323.         }  
  324.   
  325.         // headers  
  326.         if (headers != null) {  
  327.             for(String key : headers.keySet()) {  
  328.                 conn.addRequestProperty(key, headers.get(key));  
  329.             }  
  330.         }  
  331.   
  332.         // body  
  333.         if (body != null) {  
  334.             conn.setDoOutput(true);  
  335.             OutputStream os = conn.getOutputStream();  
  336.             os.write(body.getBytes());  
  337.             os.flush();  
  338.             os.close();  
  339.         }  
  340.           
  341.         // response  
  342.         InputStream is = conn.getInputStream();  
  343.         String response = streamToString(is);  
  344.         is.close();  
  345.           
  346.         // handle redirects  
  347.         if (conn.getResponseCode() == 301) {  
  348.             String location = conn.getHeaderField("Location");  
  349.             return fetch(method, location, body, headers);  
  350.         }  
  351.           
  352.         return response;  
  353.     }  
  354.       
  355.     /** 
  356.      * Read an input stream into a string 
  357.      * @param in 
  358.      * @return 
  359.      * @throws IOException 
  360.      */  
  361.     static public String streamToString(InputStream in) throws IOException {  
  362.         StringBuffer out = new StringBuffer();  
  363.         byte[] b = new byte[4096];  
  364.         for (int n; (n = in.read(b)) != -1;) {  
  365.             out.append(new String(b, 0, n));  
  366.         }  
  367.         return out.toString();  
  368.     }  
  369. }  
  370.   
  371.                       

 

阅读全文
0 0