Java笔记7:最简单的网络请求Demo

一、服务器端

 

 

1 新建一个工程,建立一个名为MyRequest的工程。

 

2 FileàProject StructureàModulesà点击最右侧的“+”àLibraryàJava

找到Tomcat中的lib目录下的servlet-api.jar,添加进来

 

 

3 建立LoginServlet类,内容如下

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.io.IOException;  
  2. import javax.servlet.ServletException;  
  3. import javax.servlet.http.HttpServlet;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6.   
  7. public class LoginServlet extends HttpServlet {  
  8.     private static final long serialVersionUID = 1L;  
  9.          
  10.     public LoginServlet() {  
  11.         super();  
  12.     }  
  13.   
  14.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  15.         this.doPost(request, response);  
  16.     }  
  17.   
  18.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  19.         String username = request.getParameter("username");  
  20.         String blog = request.getParameter("blog");  
  21.           
  22.         System.out.println(username);  
  23.         System.out.println(blog);  
  24.           
  25.         response.setContentType("text/plain; charset=UTF-8");  
  26.         response.setCharacterEncoding("UTF-8");  
  27.         response.getWriter().write("It is ok!");  
  28.     }  
  29.   
  30. }  

 

 

4 编译LoginServlet.java,得到LoginServlet.class

 

 

 

5 在Tomcat中的webapps中添加MyHttpServer\WEB-INF\classes,并把上一步生成的LoginServlet.class拷进来

 

6 在WEB-INF目录下建立web.xml文件,内容如下:

 

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>OneHttpServer</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>LoginServlet</welcome-file>  
  6.   </welcome-file-list>  
  7.     
  8.   <servlet>  
  9.     <description></description>  
  10.     <display-name>LoginServlet</display-name>  
  11.     <servlet-name>LoginServlet</servlet-name>  
  12.     <servlet-class>LoginServlet</servlet-class>  
  13.   </servlet>  
  14.   <servlet-mapping>  
  15.     <servlet-name>LoginServlet</servlet-name>  
  16.     <url-pattern>/LoginServlet</url-pattern>  
  17.   </servlet-mapping>  
  18.     
  19. </web-app>  

 

 

 

7 执行Tomcat下的bin目录下的startup.bat来启动Tomcat

 

 

8 在浏览器中输入http://localhost:8080/MyHttpServer,若见到页面显示“It is ok!”则表示服务器端配置成功。

 

二、客户端

1 Get请求

MyRequest工程新建HttpGetRequest类,内容如下:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.io.BufferedReader;  
  2. import java.io.InputStream;  
  3. import java.io.InputStreamReader;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6. import java.net.URLConnection;  
  7.   
  8. public class HttpGetRequest {  
  9.   
  10.     /** 
  11.      * Main 
  12.      * @param args 
  13.      * @throws Exception 
  14.      */  
  15.     public static void main(String[] args) throws Exception {  
  16.         System.out.println(doGet());  
  17.     }  
  18.   
  19.     /** 
  20.      * Get Request 
  21.      * @return 
  22.      * @throws Exception 
  23.      */  
  24.     public static String doGet() throws Exception {  
  25.         URL localURL = new URL("http://localhost:8080/MyHttpServer/");  
  26.         URLConnection connection = localURL.openConnection();  
  27.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;  
  28.   
  29.         httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");  
  30.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  31.   
  32.         InputStream inputStream = null;  
  33.         InputStreamReader inputStreamReader = null;  
  34.         BufferedReader reader = null;  
  35.         StringBuffer resultBuffer = new StringBuffer();  
  36.         String tempLine = null;  
  37.   
  38.         if (httpURLConnection.getResponseCode() >= 300) {  
  39.             throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  
  40.         }  
  41.   
  42.         try {  
  43.             inputStream = httpURLConnection.getInputStream();  
  44.             inputStreamReader = new InputStreamReader(inputStream);  
  45.             reader = new BufferedReader(inputStreamReader);  
  46.   
  47.             while ((tempLine = reader.readLine()) != null) {  
  48.                 resultBuffer.append(tempLine);  
  49.             }  
  50.   
  51.         } finally {  
  52.   
  53.             if (reader != null) {  
  54.                 reader.close();  
  55.             }  
  56.   
  57.             if (inputStreamReader != null) {  
  58.                 inputStreamReader.close();  
  59.             }  
  60.   
  61.             if (inputStream != null) {  
  62.                 inputStream.close();  
  63.             }  
  64.   
  65.         }  
  66.   
  67.         return resultBuffer.toString();  
  68.     }  
  69.   
  70. }  

 

 

运行结果:

It is ok!

 

2 Post请求

新建HttpPostRequest.java类,内容如下:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.io.BufferedReader;  
  2. import java.io.InputStream;  
  3. import java.io.InputStreamReader;  
  4. import java.io.OutputStream;  
  5. import java.io.OutputStreamWriter;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8. import java.net.URLConnection;  
  9.   
  10. public class HttpPostRequest {  
  11.   
  12.     /** 
  13.      * Main 
  14.      * @param args 
  15.      * @throws Exception 
  16.      */  
  17.     public static void main(String[] args) throws Exception {  
  18.         System.out.println(doPost());  
  19.     }  
  20.   
  21.     /** 
  22.      * Post Request 
  23.      * @return 
  24.      * @throws Exception 
  25.      */  
  26.     public static String doPost() throws Exception {  
  27.         String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";  
  28.   
  29.         URL localURL = new URL("http://localhost:8080/MyHttpServer/");  
  30.         URLConnection connection = localURL.openConnection();  
  31.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;  
  32.   
  33.         httpURLConnection.setDoOutput(true);  
  34.         httpURLConnection.setRequestMethod("POST");  
  35.         httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");  
  36.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  37.         httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));  
  38.   
  39.         OutputStream outputStream = null;  
  40.         OutputStreamWriter outputStreamWriter = null;  
  41.         InputStream inputStream = null;  
  42.         InputStreamReader inputStreamReader = null;  
  43.         BufferedReader reader = null;  
  44.         StringBuffer resultBuffer = new StringBuffer();  
  45.         String tempLine = null;  
  46.   
  47.         try {  
  48.             outputStream = httpURLConnection.getOutputStream();  
  49.             outputStreamWriter = new OutputStreamWriter(outputStream);  
  50.   
  51.             outputStreamWriter.write(parameterData.toString());  
  52.             outputStreamWriter.flush();  
  53.   
  54.             if (httpURLConnection.getResponseCode() >= 300) {  
  55.                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  
  56.             }  
  57.   
  58.             inputStream = httpURLConnection.getInputStream();  
  59.             inputStreamReader = new InputStreamReader(inputStream);  
  60.             reader = new BufferedReader(inputStreamReader);  
  61.   
  62.             while ((tempLine = reader.readLine()) != null) {  
  63.                 resultBuffer.append(tempLine);  
  64.             }  
  65.   
  66.         } finally {  
  67.   
  68.             if (outputStreamWriter != null) {  
  69.                 outputStreamWriter.close();  
  70.             }  
  71.   
  72.             if (outputStream != null) {  
  73.                 outputStream.close();  
  74.             }  
  75.   
  76.             if (reader != null) {  
  77.                 reader.close();  
  78.             }  
  79.   
  80.             if (inputStreamReader != null) {  
  81.                 inputStreamReader.close();  
  82.             }  
  83.   
  84.             if (inputStream != null) {  
  85.                 inputStream.close();  
  86.             }  
  87.   
  88.         }  
  89.   
  90.         return resultBuffer.toString();  
  91.     }  
  92. }  

 

 

运行结果:

It is ok!

 

3 对Get和Post进行封装

封装类:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.io.OutputStream;  
  6. import java.io.OutputStreamWriter;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.InetSocketAddress;  
  9. import java.net.Proxy;  
  10. import java.net.URL;  
  11. import java.net.URLConnection;  
  12. import java.util.Iterator;  
  13. import java.util.Map;  
  14.   
  15.   
  16. public class HttpRequestor {  
  17.   
  18.     private String charset = "utf-8";  
  19.     private Integer connectTimeout = null;  
  20.     private Integer socketTimeout = null;  
  21.     private String proxyHost = null;  
  22.     private Integer proxyPort = null;  
  23.   
  24.     /** 
  25.      * Do GET request 
  26.      * @param url 
  27.      * @return 
  28.      * @throws Exception 
  29.      * @throws IOException 
  30.      */  
  31.     public String doGet(String url) throws Exception {  
  32.   
  33.         URL localURL = new URL(url);  
  34.   
  35.         URLConnection connection = openConnection(localURL);  
  36.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;  
  37.   
  38.         httpURLConnection.setRequestProperty("Accept-Charset", charset);  
  39.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  40.   
  41.         InputStream inputStream = null;  
  42.         InputStreamReader inputStreamReader = null;  
  43.         BufferedReader reader = null;  
  44.         StringBuffer resultBuffer = new StringBuffer();  
  45.         String tempLine = null;  
  46.   
  47.         if (httpURLConnection.getResponseCode() >= 300) {  
  48.             throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  
  49.         }  
  50.   
  51.         try {  
  52.             inputStream = httpURLConnection.getInputStream();  
  53.             inputStreamReader = new InputStreamReader(inputStream);  
  54.             reader = new BufferedReader(inputStreamReader);  
  55.   
  56.             while ((tempLine = reader.readLine()) != null) {  
  57.                 resultBuffer.append(tempLine);  
  58.             }  
  59.   
  60.         } finally {  
  61.   
  62.             if (reader != null) {  
  63.                 reader.close();  
  64.             }  
  65.   
  66.             if (inputStreamReader != null) {  
  67.                 inputStreamReader.close();  
  68.             }  
  69.   
  70.             if (inputStream != null) {  
  71.                 inputStream.close();  
  72.             }  
  73.   
  74.         }  
  75.   
  76.         return resultBuffer.toString();  
  77.     }  
  78.   
  79.     /** 
  80.      * Do POST request 
  81.      * @param url 
  82.      * @param parameterMap 
  83.      * @return 
  84.      * @throws Exception 
  85.      */  
  86.     public String doPost(String url, Map parameterMap) throws Exception {  
  87.           
  88.         /* Translate parameter map to parameter date string */  
  89.         StringBuffer parameterBuffer = new StringBuffer();  
  90.         if (parameterMap != null) {  
  91.             Iterator iterator = parameterMap.keySet().iterator();  
  92.             String key = null;  
  93.             String value = null;  
  94.             while (iterator.hasNext()) {  
  95.                 key = (String)iterator.next();  
  96.                 if (parameterMap.get(key) != null) {  
  97.                     value = (String)parameterMap.get(key);  
  98.                 } else {  
  99.                     value = "";  
  100.                 }  
  101.   
  102.                 parameterBuffer.append(key).append("=").append(value);  
  103.                 if (iterator.hasNext()) {  
  104.                     parameterBuffer.append("&");  
  105.                 }  
  106.             }  
  107.         }  
  108.   
  109.         System.out.println("POST parameter : " + parameterBuffer.toString());  
  110.   
  111.         URL localURL = new URL(url);  
  112.   
  113.         URLConnection connection = openConnection(localURL);  
  114.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;  
  115.   
  116.         httpURLConnection.setDoOutput(true);  
  117.         httpURLConnection.setRequestMethod("POST");  
  118.         httpURLConnection.setRequestProperty("Accept-Charset", charset);  
  119.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  120.         httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));  
  121.   
  122.         OutputStream outputStream = null;  
  123.         OutputStreamWriter outputStreamWriter = null;  
  124.         InputStream inputStream = null;  
  125.         InputStreamReader inputStreamReader = null;  
  126.         BufferedReader reader = null;  
  127.         StringBuffer resultBuffer = new StringBuffer();  
  128.         String tempLine = null;  
  129.   
  130.         try {  
  131.             outputStream = httpURLConnection.getOutputStream();  
  132.             outputStreamWriter = new OutputStreamWriter(outputStream);  
  133.   
  134.             outputStreamWriter.write(parameterBuffer.toString());  
  135.             outputStreamWriter.flush();  
  136.   
  137.             if (httpURLConnection.getResponseCode() >= 300) {  
  138.                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  
  139.             }  
  140.   
  141.             inputStream = httpURLConnection.getInputStream();  
  142.             inputStreamReader = new InputStreamReader(inputStream);  
  143.             reader = new BufferedReader(inputStreamReader);  
  144.   
  145.             while ((tempLine = reader.readLine()) != null) {  
  146.                 resultBuffer.append(tempLine);  
  147.             }  
  148.   
  149.         } finally {  
  150.   
  151.             if (outputStreamWriter != null) {  
  152.                 outputStreamWriter.close();  
  153.             }  
  154.   
  155.             if (outputStream != null) {  
  156.                 outputStream.close();  
  157.             }  
  158.   
  159.             if (reader != null) {  
  160.                 reader.close();  
  161.             }  
  162.   
  163.             if (inputStreamReader != null) {  
  164.                 inputStreamReader.close();  
  165.             }  
  166.   
  167.             if (inputStream != null) {  
  168.                 inputStream.close();  
  169.             }  
  170.   
  171.         }  
  172.   
  173.         return resultBuffer.toString();  
  174.     }  
  175.   
  176.     private URLConnection openConnection(URL localURL) throws IOException {  
  177.         URLConnection connection;  
  178.         if (proxyHost != null && proxyPort != null) {  
  179.             Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));  
  180.             connection = localURL.openConnection(proxy);  
  181.         } else {  
  182.             connection = localURL.openConnection();  
  183.         }  
  184.         return connection;  
  185.     }  
  186.   
  187.     /** 
  188.      * Render request according setting 
  189.      * @param request 
  190.      */  
  191.     private void renderRequest(URLConnection connection) {  
  192.   
  193.         if (connectTimeout != null) {  
  194.             connection.setConnectTimeout(connectTimeout);  
  195.         }  
  196.   
  197.         if (socketTimeout != null) {  
  198.             connection.setReadTimeout(socketTimeout);  
  199.         }  
  200.   
  201.     }  
  202.   
  203.     /* 
  204.      * Getter & Setter 
  205.      */  
  206.     public Integer getConnectTimeout() {  
  207.         return connectTimeout;  
  208.     }  
  209.   
  210.     public void setConnectTimeout(Integer connectTimeout) {  
  211.         this.connectTimeout = connectTimeout;  
  212.     }  
  213.   
  214.     public Integer getSocketTimeout() {  
  215.         return socketTimeout;  
  216.     }  
  217.   
  218.     public void setSocketTimeout(Integer socketTimeout) {  
  219.         this.socketTimeout = socketTimeout;  
  220.     }  
  221.   
  222.     public String getProxyHost() {  
  223.         return proxyHost;  
  224.     }  
  225.   
  226.     public void setProxyHost(String proxyHost) {  
  227.         this.proxyHost = proxyHost;  
  228.     }  
  229.   
  230.     public Integer getProxyPort() {  
  231.         return proxyPort;  
  232.     }  
  233.   
  234.     public void setProxyPort(Integer proxyPort) {  
  235.         this.proxyPort = proxyPort;  
  236.     }  
  237.   
  238.     public String getCharset() {  
  239.         return charset;  
  240.     }  
  241.   
  242.     public void setCharset(String charset) {  
  243.         this.charset = charset;  
  244.     }  
  245.   
  246. }  

 

 

 

客户端测试代码:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3.   
  4. public class Call {  
  5.   
  6.     public static void main(String[] args) throws Exception {  
  7.   
  8.         /* Post Request */  
  9.         Map dataMap = new HashMap();  
  10.         dataMap.put("username", "Zheng");  
  11.         dataMap.put("blog", "IT");  
  12.         System.out.println(new HttpRequestor().doPost("http://localhost:8080/MyHttpServer/", dataMap));  
  13.   
  14.         /* Get Request */  
  15.         System.out.println(new HttpRequestor().doGet("http://localhost:8080/MyHttpServer/"));  
  16.     }  
  17. }  

 

 

运行结果:

POST parameter : blog=IT&username=Zheng

It is ok!

It is ok!

posted @ 2017-04-19 11:16  爱你爱自己  阅读(479)  评论(0编辑  收藏  举报