JAVA发送HTTP请求,返回HTTP响应内容,实例及应用

来源:互联网 发布:linux修改用户密码命令 编辑:程序博客网 时间:2024/05/16 01:32

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

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

该类封装了 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. }  

 

 

其次我们来看看响应对象(HttpRespons )。 响应对象其实只是一个数据BEAN ,由此来封装请求响应的结果数据,如下:
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. }  

 

 

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

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 0