JAVA不使用第三方jar发送HTTP请求,并接受返回内容

JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述: 

首先让我们先构建一个请求类(HttpRequester )。 

该类封装了 JAVA 实现简单请求的代码,如下: 


Java代码 
Java代码   收藏代码
  1. import java.io.BufferedReader;     
  2. import java.io.IOException;     
  3. import java.io.InputStream;     
  4. import java.io.InputStreamReader;     
  5. import java.net.HttpURLConnection;     
  6. import java.net.URL;     
  7. import java.nio.charset.Charset;     
  8. import java.util.Map;     
  9. import java.util.Vector;     
  10.       
  11. /**   
  12.  * HTTP请求对象   
  13.  *    
  14.  * @author YYmmiinngg   
  15.  */    
  16. public class HttpRequester {     
  17.     private String defaultContentEncoding;     
  18.       
  19.     public HttpRequester() {     
  20.         this.defaultContentEncoding = Charset.defaultCharset().name();     
  21.     }     
  22.       
  23.     /**   
  24.      * 发送GET请求   
  25.      *    
  26.      * @param urlString   
  27.      *            URL地址   
  28.      * @return 响应对象   
  29.      * @throws IOException   
  30.      */    
  31.     public HttpRespons sendGet(String urlString) throws IOException {     
  32.         return this.send(urlString, "GET"nullnull);     
  33.     }     
  34.       
  35.     /**   
  36.      * 发送GET请求   
  37.      *    
  38.      * @param urlString   
  39.      *            URL地址   
  40.      * @param params   
  41.      *            参数集合   
  42.      * @return 响应对象   
  43.      * @throws IOException   
  44.      */    
  45.     public HttpRespons sendGet(String urlString, Map<String, String> params)     
  46.             throws IOException {     
  47.         return this.send(urlString, "GET", params, null);     
  48.     }     
  49.       
  50.     /**   
  51.      * 发送GET请求   
  52.      *    
  53.      * @param urlString   
  54.      *            URL地址   
  55.      * @param params   
  56.      *            参数集合   
  57.      * @param propertys   
  58.      *            请求属性   
  59.      * @return 响应对象   
  60.      * @throws IOException   
  61.      */    
  62.     public HttpRespons sendGet(String urlString, Map<String, String> params,     
  63.             Map<String, String> propertys) throws IOException {     
  64.         return this.send(urlString, "GET", params, propertys);     
  65.     }     
  66.       
  67.     /**   
  68.      * 发送POST请求   
  69.      *    
  70.      * @param urlString   
  71.      *            URL地址   
  72.      * @return 响应对象   
  73.      * @throws IOException   
  74.      */    
  75.     public HttpRespons sendPost(String urlString) throws IOException {     
  76.         return this.send(urlString, "POST"nullnull);     
  77.     }     
  78.       
  79.     /**   
  80.      * 发送POST请求   
  81.      *    
  82.      * @param urlString   
  83.      *            URL地址   
  84.      * @param params   
  85.      *            参数集合   
  86.      * @return 响应对象   
  87.      * @throws IOException   
  88.      */    
  89.     public HttpRespons sendPost(String urlString, Map<String, String> params)     
  90.             throws IOException {     
  91.         return this.send(urlString, "POST", params, null);     
  92.     }     
  93.       
  94.     /**   
  95.      * 发送POST请求   
  96.      *    
  97.      * @param urlString   
  98.      *            URL地址   
  99.      * @param params   
  100.      *            参数集合   
  101.      * @param propertys   
  102.      *            请求属性   
  103.      * @return 响应对象   
  104.      * @throws IOException   
  105.      */    
  106.     public HttpRespons sendPost(String urlString, Map<String, String> params,     
  107.             Map<String, String> propertys) throws IOException {     
  108.         return this.send(urlString, "POST", params, propertys);     
  109.     }     
  110.       
  111.     /**   
  112.      * 发送HTTP请求   
  113.      *    
  114.      * @param urlString   
  115.      * @return 响映对象   
  116.      * @throws IOException   
  117.      */    
  118.     private HttpRespons send(String urlString, String method,     
  119.             Map<String, String> parameters, Map<String, String> propertys)     
  120.             throws IOException {     
  121.         HttpURLConnection urlConnection = null;     
  122.       
  123.         if (method.equalsIgnoreCase("GET") && parameters != null) {     
  124.             StringBuffer param = new StringBuffer();     
  125.             int i = 0;     
  126.             for (String key : parameters.keySet()) {     
  127.                 if (i == 0)     
  128.                     param.append("?");     
  129.                 else    
  130.                     param.append("&");     
  131.                 param.append(key).append("=").append(parameters.get(key));     
  132.                 i++;     
  133.             }     
  134.             urlString += param;     
  135.         }     
  136.         URL url = new URL(urlString);     
  137.         urlConnection = (HttpURLConnection) url.openConnection();     
  138.       
  139.         urlConnection.setRequestMethod(method);     
  140.         urlConnection.setDoOutput(true);     
  141.         urlConnection.setDoInput(true);     
  142.         urlConnection.setUseCaches(false);     
  143.       
  144.         if (propertys != null)     
  145.             for (String key : propertys.keySet()) {     
  146.                 urlConnection.addRequestProperty(key, propertys.get(key));     
  147.             }     
  148.       
  149.         if (method.equalsIgnoreCase("POST") && parameters != null) {     
  150.             StringBuffer param = new StringBuffer();     
  151.             for (String key : parameters.keySet()) {     
  152.                 param.append("&");     
  153.                 param.append(key).append("=").append(parameters.get(key));     
  154.             }     
  155.             urlConnection.getOutputStream().write(param.toString().getBytes());     
  156.             urlConnection.getOutputStream().flush();     
  157.             urlConnection.getOutputStream().close();     
  158.         }     
  159.       
  160.         return this.makeContent(urlString, urlConnection);     
  161.     }     
  162.       
  163.     /**   
  164.      * 得到响应对象   
  165.      *    
  166.      * @param urlConnection   
  167.      * @return 响应对象   
  168.      * @throws IOException   
  169.      */    
  170.     private HttpRespons makeContent(String urlString,     
  171.             HttpURLConnection urlConnection) throws IOException {     
  172.         HttpRespons httpResponser = new HttpRespons();     
  173.         try {     
  174.             InputStream in = urlConnection.getInputStream();     
  175.             BufferedReader bufferedReader = new BufferedReader(     
  176.                     new InputStreamReader(in));     
  177.             httpResponser.contentCollection = new Vector<String>();     
  178.             StringBuffer temp = new StringBuffer();     
  179.             String line = bufferedReader.readLine();     
  180.             while (line != null) {     
  181.                 httpResponser.contentCollection.add(line);     
  182.                 temp.append(line).append("\r\n");     
  183.                 line = bufferedReader.readLine();     
  184.             }     
  185.             bufferedReader.close();     
  186.       
  187.             String ecod = urlConnection.getContentEncoding();     
  188.             if (ecod == null)     
  189.                 ecod = this.defaultContentEncoding;     
  190.       
  191.             httpResponser.urlString = urlString;     
  192.       
  193.             httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();     
  194.             httpResponser.file = urlConnection.getURL().getFile();     
  195.             httpResponser.host = urlConnection.getURL().getHost();     
  196.             httpResponser.path = urlConnection.getURL().getPath();     
  197.             httpResponser.port = urlConnection.getURL().getPort();     
  198.             httpResponser.protocol = urlConnection.getURL().getProtocol();     
  199.             httpResponser.query = urlConnection.getURL().getQuery();     
  200.             httpResponser.ref = urlConnection.getURL().getRef();     
  201.             httpResponser.userInfo = urlConnection.getURL().getUserInfo();     
  202.       
  203.             httpResponser.content = new String(temp.toString().getBytes(), ecod);     
  204.             httpResponser.contentEncoding = ecod;     
  205.             httpResponser.code = urlConnection.getResponseCode();     
  206.             httpResponser.message = urlConnection.getResponseMessage();     
  207.             httpResponser.contentType = urlConnection.getContentType();     
  208.             httpResponser.method = urlConnection.getRequestMethod();     
  209.             httpResponser.connectTimeout = urlConnection.getConnectTimeout();     
  210.             httpResponser.readTimeout = urlConnection.getReadTimeout();     
  211.       
  212.             return httpResponser;     
  213.         } catch (IOException e) {     
  214.             throw e;     
  215.         } finally {     
  216.             if (urlConnection != null)     
  217.                 urlConnection.disconnect();     
  218.         }     
  219.     }     
  220.       
  221.     /**   
  222.      * 默认的响应字符集   
  223.      */    
  224.     public String getDefaultContentEncoding() {     
  225.         return this.defaultContentEncoding;     
  226.     }     
  227.       
  228.     /**   
  229.      * 设置默认的响应字符集   
  230.      */    
  231.     public void setDefaultContentEncoding(String defaultContentEncoding) {     
  232.         this.defaultContentEncoding = defaultContentEncoding;     
  233.     }     
  234. }    
  235.   
  236. import java.io.BufferedReader;  
  237. import java.io.IOException;  
  238. import java.io.InputStream;  
  239. import java.io.InputStreamReader;  
  240. import java.net.HttpURLConnection;  
  241. import java.net.URL;  
  242. import java.nio.charset.Charset;  
  243. import java.util.Map;  
  244. import java.util.Vector;  
  245.    
  246. /** 
  247.  * HTTP请求对象 
  248.  *  
  249.  * @author YYmmiinngg 
  250.  */  
  251. public class HttpRequester {  
  252.     private String defaultContentEncoding;  
  253.    
  254.     public HttpRequester() {  
  255.         this.defaultContentEncoding = Charset.defaultCharset().name();  
  256.     }  
  257.    
  258.     /** 
  259.      * 发送GET请求 
  260.      *  
  261.      * @param urlString 
  262.      *            URL地址 
  263.      * @return 响应对象 
  264.      * @throws IOException 
  265.      */  
  266.     public HttpRespons sendGet(String urlString) throws IOException {  
  267.         return this.send(urlString, "GET"nullnull);  
  268.     }  
  269.    
  270.     /** 
  271.      * 发送GET请求 
  272.      *  
  273.      * @param urlString 
  274.      *            URL地址 
  275.      * @param params 
  276.      *            参数集合 
  277.      * @return 响应对象 
  278.      * @throws IOException 
  279.      */  
  280.     public HttpRespons sendGet(String urlString, Map<String, String> params)  
  281.             throws IOException {  
  282.         return this.send(urlString, "GET", params, null);  
  283.     }  
  284.    
  285.     /** 
  286.      * 发送GET请求 
  287.      *  
  288.      * @param urlString 
  289.      *            URL地址 
  290.      * @param params 
  291.      *            参数集合 
  292.      * @param propertys 
  293.      *            请求属性 
  294.      * @return 响应对象 
  295.      * @throws IOException 
  296.      */  
  297.     public HttpRespons sendGet(String urlString, Map<String, String> params,  
  298.             Map<String, String> propertys) throws IOException {  
  299.         return this.send(urlString, "GET", params, propertys);  
  300.     }  
  301.    
  302.     /** 
  303.      * 发送POST请求 
  304.      *  
  305.      * @param urlString 
  306.      *            URL地址 
  307.      * @return 响应对象 
  308.      * @throws IOException 
  309.      */  
  310.     public HttpRespons sendPost(String urlString) throws IOException {  
  311.         return this.send(urlString, "POST"nullnull);  
  312.     }  
  313.    
  314.     /** 
  315.      * 发送POST请求 
  316.      *  
  317.      * @param urlString 
  318.      *            URL地址 
  319.      * @param params 
  320.      *            参数集合 
  321.      * @return 响应对象 
  322.      * @throws IOException 
  323.      */  
  324.     public HttpRespons sendPost(String urlString, Map<String, String> params)  
  325.             throws IOException {  
  326.         return this.send(urlString, "POST", params, null);  
  327.     }  
  328.    
  329.     /** 
  330.      * 发送POST请求 
  331.      *  
  332.      * @param urlString 
  333.      *            URL地址 
  334.      * @param params 
  335.      *            参数集合 
  336.      * @param propertys 
  337.      *            请求属性 
  338.      * @return 响应对象 
  339.      * @throws IOException 
  340.      */  
  341.     public HttpRespons sendPost(String urlString, Map<String, String> params,  
  342.             Map<String, String> propertys) throws IOException {  
  343.         return this.send(urlString, "POST", params, propertys);  
  344.     }  
  345.    
  346.     /** 
  347.      * 发送HTTP请求 
  348.      *  
  349.      * @param urlString 
  350.      * @return 响映对象 
  351.      * @throws IOException 
  352.      */  
  353.     private HttpRespons send(String urlString, String method,  
  354.             Map<String, String> parameters, Map<String, String> propertys)  
  355.             throws IOException {  
  356.         HttpURLConnection urlConnection = null;  
  357.    
  358.         if (method.equalsIgnoreCase("GET") && parameters != null) {  
  359.             StringBuffer param = new StringBuffer();  
  360.             int i = 0;  
  361.             for (String key : parameters.keySet()) {  
  362.                 if (i == 0)  
  363.                     param.append("?");  
  364.                 else  
  365.                     param.append("&");  
  366.                 param.append(key).append("=").append(parameters.get(key));  
  367.                 i++;  
  368.             }  
  369.             urlString += param;  
  370.         }  
  371.         URL url = new URL(urlString);  
  372.         urlConnection = (HttpURLConnection) url.openConnection();  
  373.    
  374.         urlConnection.setRequestMethod(method);  
  375.         urlConnection.setDoOutput(true);  
  376.         urlConnection.setDoInput(true);  
  377.         urlConnection.setUseCaches(false);  
  378.    
  379.         if (propertys != null)  
  380.             for (String key : propertys.keySet()) {  
  381.                 urlConnection.addRequestProperty(key, propertys.get(key));  
  382.             }  
  383.    
  384.         if (method.equalsIgnoreCase("POST") && parameters != null) {  
  385.             StringBuffer param = new StringBuffer();  
  386.             for (String key : parameters.keySet()) {  
  387.                 param.append("&");  
  388.                 param.append(key).append("=").append(parameters.get(key));  
  389.             }  
  390.             urlConnection.getOutputStream().write(param.toString().getBytes());  
  391.             urlConnection.getOutputStream().flush();  
  392.             urlConnection.getOutputStream().close();  
  393.         }  
  394.    
  395.         return this.makeContent(urlString, urlConnection);  
  396.     }  
  397.    
  398.     /** 
  399.      * 得到响应对象 
  400.      *  
  401.      * @param urlConnection 
  402.      * @return 响应对象 
  403.      * @throws IOException 
  404.      */  
  405.     private HttpRespons makeContent(String urlString,  
  406.             HttpURLConnection urlConnection) throws IOException {  
  407.         HttpRespons httpResponser = new HttpRespons();  
  408.         try {  
  409.             InputStream in = urlConnection.getInputStream();  
  410.             BufferedReader bufferedReader = new BufferedReader(  
  411.                     new InputStreamReader(in));  
  412.             httpResponser.contentCollection = new Vector<String>();  
  413.             StringBuffer temp = new StringBuffer();  
  414.             String line = bufferedReader.readLine();  
  415.             while (line != null) {  
  416.                 httpResponser.contentCollection.add(line);  
  417.                 temp.append(line).append("\r\n");  
  418.                 line = bufferedReader.readLine();  
  419.             }  
  420.             bufferedReader.close();  
  421.    
  422.             String ecod = urlConnection.getContentEncoding();  
  423.             if (ecod == null)  
  424.                 ecod = this.defaultContentEncoding;  
  425.    
  426.             httpResponser.urlString = urlString;  
  427.    
  428.             httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();  
  429.             httpResponser.file = urlConnection.getURL().getFile();  
  430.             httpResponser.host = urlConnection.getURL().getHost();  
  431.             httpResponser.path = urlConnection.getURL().getPath();  
  432.             httpResponser.port = urlConnection.getURL().getPort();  
  433.             httpResponser.protocol = urlConnection.getURL().getProtocol();  
  434.             httpResponser.query = urlConnection.getURL().getQuery();  
  435.             httpResponser.ref = urlConnection.getURL().getRef();  
  436.             httpResponser.userInfo = urlConnection.getURL().getUserInfo();  
  437.    
  438.             httpResponser.content = new String(temp.toString().getBytes(), ecod);  
  439.             httpResponser.contentEncoding = ecod;  
  440.             httpResponser.code = urlConnection.getResponseCode();  
  441.             httpResponser.message = urlConnection.getResponseMessage();  
  442.             httpResponser.contentType = urlConnection.getContentType();  
  443.             httpResponser.method = urlConnection.getRequestMethod();  
  444.             httpResponser.connectTimeout = urlConnection.getConnectTimeout();  
  445.             httpResponser.readTimeout = urlConnection.getReadTimeout();  
  446.    
  447.             return httpResponser;  
  448.         } catch (IOException e) {  
  449.             throw e;  
  450.         } finally {  
  451.             if (urlConnection != null)  
  452.                 urlConnection.disconnect();  
  453.         }  
  454.     }  
  455.    
  456.     /** 
  457.      * 默认的响应字符集 
  458.      */  
  459.     public String getDefaultContentEncoding() {  
  460.         return this.defaultContentEncoding;  
  461.     }  
  462.    
  463.     /** 
  464.      * 设置默认的响应字符集 
  465.      */  
  466.     public void setDefaultContentEncoding(String defaultContentEncoding) {  
  467.         this.defaultContentEncoding = defaultContentEncoding;  
  468.     }  
  469. }  
  470.    




其次我们来看看响应对象(HttpRespons )。 响应对象其实只是一个数据BEAN ,由此来封装请求响应的结果数据,如下: Java代码 
Java代码   收藏代码
  1. import java.util.Vector;     
  2.       
  3. /**   
  4.  * 响应对象   
  5.  */    
  6. public class HttpRespons {     
  7.       
  8.     String urlString;     
  9.       
  10.     int defaultPort;     
  11.       
  12.     String file;     
  13.       
  14.     String host;     
  15.       
  16.     String path;     
  17.       
  18.     int port;     
  19.       
  20.     String protocol;     
  21.       
  22.     String query;     
  23.       
  24.     String ref;     
  25.       
  26.     String userInfo;     
  27.       
  28.     String contentEncoding;     
  29.       
  30.     String content;     
  31.       
  32.     String contentType;     
  33.       
  34.     int code;     
  35.       
  36.     String message;     
  37.       
  38.     String method;     
  39.       
  40.     int connectTimeout;     
  41.       
  42.     int readTimeout;     
  43.       
  44.     Vector<String> contentCollection;     
  45.       
  46.     public String getContent() {     
  47.         return content;     
  48.     }     
  49.       
  50.     public String getContentType() {     
  51.         return contentType;     
  52.     }     
  53.       
  54.     public int getCode() {     
  55.         return code;     
  56.     }     
  57.       
  58.     public String getMessage() {     
  59.         return message;     
  60.     }     
  61.       
  62.     public Vector<String> getContentCollection() {     
  63.         return contentCollection;     
  64.     }     
  65.       
  66.     public String getContentEncoding() {     
  67.         return contentEncoding;     
  68.     }     
  69.       
  70.     public String getMethod() {     
  71.         return method;     
  72.     }     
  73.       
  74.     public int getConnectTimeout() {     
  75.         return connectTimeout;     
  76.     }     
  77.       
  78.     public int getReadTimeout() {     
  79.         return readTimeout;     
  80.     }     
  81.       
  82.     public String getUrlString() {     
  83.         return urlString;     
  84.     }     
  85.       
  86.     public int getDefaultPort() {     
  87.         return defaultPort;     
  88.     }     
  89.       
  90.     public String getFile() {     
  91.         return file;     
  92.     }     
  93.       
  94.     public String getHost() {     
  95.         return host;     
  96.     }     
  97.       
  98.     public String getPath() {     
  99.         return path;     
  100.     }     
  101.       
  102.     public int getPort() {     
  103.         return port;     
  104.     }     
  105.       
  106.     public String getProtocol() {     
  107.         return protocol;     
  108.     }     
  109.       
  110.     public String getQuery() {     
  111.         return query;     
  112.     }     
  113.       
  114.     public String getRef() {     
  115.         return ref;     
  116.     }     
  117.       
  118.     public String getUserInfo() {     
  119.         return userInfo;     
  120.     }     
  121.       
  122. }    
  123.   
  124. import java.util.Vector;  
  125.    
  126. /** 
  127.  * 响应对象 
  128.  */  
  129. public class HttpRespons {  
  130.    
  131.     String urlString;  
  132.    
  133.     int defaultPort;  
  134.    
  135.     String file;  
  136.    
  137.     String host;  
  138.    
  139.     String path;  
  140.    
  141.     int port;  
  142.    
  143.     String protocol;  
  144.    
  145.     String query;  
  146.    
  147.     String ref;  
  148.    
  149.     String userInfo;  
  150.    
  151.     String contentEncoding;  
  152.    
  153.     String content;  
  154.    
  155.     String contentType;  
  156.    
  157.     int code;  
  158.    
  159.     String message;  
  160.    
  161.     String method;  
  162.    
  163.     int connectTimeout;  
  164.    
  165.     int readTimeout;  
  166.    
  167.     Vector<String> contentCollection;  
  168.    
  169.     public String getContent() {  
  170.         return content;  
  171.     }  
  172.    
  173.     public String getContentType() {  
  174.         return contentType;  
  175.     }  
  176.    
  177.     public int getCode() {  
  178.         return code;  
  179.     }  
  180.    
  181.     public String getMessage() {  
  182.         return message;  
  183.     }  
  184.    
  185.     public Vector<String> getContentCollection() {  
  186.         return contentCollection;  
  187.     }  
  188.    
  189.     public String getContentEncoding() {  
  190.         return contentEncoding;  
  191.     }  
  192.    
  193.     public String getMethod() {  
  194.         return method;  
  195.     }  
  196.    
  197.     public int getConnectTimeout() {  
  198.         return connectTimeout;  
  199.     }  
  200.    
  201.     public int getReadTimeout() {  
  202.         return readTimeout;  
  203.     }  
  204.    
  205.     public String getUrlString() {  
  206.         return urlString;  
  207.     }  
  208.    
  209.     public int getDefaultPort() {  
  210.         return defaultPort;  
  211.     }  
  212.    
  213.     public String getFile() {  
  214.         return file;  
  215.     }  
  216.    
  217.     public String getHost() {  
  218.         return host;  
  219.     }  
  220.    
  221.     public String getPath() {  
  222.         return path;  
  223.     }  
  224.    
  225.     public int getPort() {  
  226.         return port;  
  227.     }  
  228.    
  229.     public String getProtocol() {  
  230.         return protocol;  
  231.     }  
  232.    
  233.     public String getQuery() {  
  234.         return query;  
  235.     }  
  236.    
  237.     public String getRef() {  
  238.         return ref;  
  239.     }  
  240.    
  241.     public String getUserInfo() {  
  242.         return userInfo;  
  243.     }  
  244.    
  245. }  




最后,让我们写一个应用类,测试以上代码是否正确 

Java代码 
Java代码   收藏代码
  1. import com.yao.http.HttpRequester;     
  2. import com.yao.http.HttpRespons;     
  3.       
  4. public class Test {     
  5.     public static void main(String[] args) {     
  6.         try {     
  7.             HttpRequester request = new HttpRequester();     
  8.             HttpRespons hr = request.sendGet("http://www.csdn.net");     
  9.       
  10.             System.out.println(hr.getUrlString());     
  11.             System.out.println(hr.getProtocol());     
  12.             System.out.println(hr.getHost());     
  13.             System.out.println(hr.getPort());     
  14.             System.out.println(hr.getContentEncoding());     
  15.             System.out.println(hr.getMethod());     
  16.                  
  17.             System.out.println(hr.getContent());     
  18.       
  19.         } catch (Exception e) {     
  20.             e.printStackTrace();     
  21.         }     
  22.     }     
  23. }   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值