一、服务器端

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

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

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

3 建立LoginServlet类,内容如下

  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. public class LoginServlet extends HttpServlet {
  7. private static final long serialVersionUID = 1L;
  8. public LoginServlet() {
  9. super();
  10. }
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. this.doPost(request, response);
  13. }
  14. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  15. String username = request.getParameter("username");
  16. String blog = request.getParameter("blog");
  17. System.out.println(username);
  18. System.out.println(blog);
  19. response.setContentType("text/plain; charset=UTF-8");
  20. response.setCharacterEncoding("UTF-8");
  21. response.getWriter().write("It is ok!");
  22. }
  23. }

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

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

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

  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. <servlet>
  8. <description></description>
  9. <display-name>LoginServlet</display-name>
  10. <servlet-name>LoginServlet</servlet-name>
  11. <servlet-class>LoginServlet</servlet-class>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>LoginServlet</servlet-name>
  15. <url-pattern>/LoginServlet</url-pattern>
  16. </servlet-mapping>
  17. </web-app>

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

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

二、客户端

1 Get请求

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

  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. public class HttpGetRequest {
  8. /**
  9. * Main
  10. * @param args
  11. * @throws Exception
  12. */
  13. public static void main(String[] args) throws Exception {
  14. System.out.println(doGet());
  15. }
  16. /**
  17. * Get Request
  18. * @return
  19. * @throws Exception
  20. */
  21. public static String doGet() throws Exception {
  22. URL localURL = new URL("http://localhost:8080/MyHttpServer/");
  23. URLConnection connection = localURL.openConnection();
  24. HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
  25. httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
  26. httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  27. InputStream inputStream = null;
  28. InputStreamReader inputStreamReader = null;
  29. BufferedReader reader = null;
  30. StringBuffer resultBuffer = new StringBuffer();
  31. String tempLine = null;
  32. if (httpURLConnection.getResponseCode() >= 300) {
  33. throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
  34. }
  35. try {
  36. inputStream = httpURLConnection.getInputStream();
  37. inputStreamReader = new InputStreamReader(inputStream);
  38. reader = new BufferedReader(inputStreamReader);
  39. while ((tempLine = reader.readLine()) != null) {
  40. resultBuffer.append(tempLine);
  41. }
  42. } finally {
  43. if (reader != null) {
  44. reader.close();
  45. }
  46. if (inputStreamReader != null) {
  47. inputStreamReader.close();
  48. }
  49. if (inputStream != null) {
  50. inputStream.close();
  51. }
  52. }
  53. return resultBuffer.toString();
  54. }
  55. }

运行结果:

It is ok!

2 Post请求

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

  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. public class HttpPostRequest {
  10. /**
  11. * Main
  12. * @param args
  13. * @throws Exception
  14. */
  15. public static void main(String[] args) throws Exception {
  16. System.out.println(doPost());
  17. }
  18. /**
  19. * Post Request
  20. * @return
  21. * @throws Exception
  22. */
  23. public static String doPost() throws Exception {
  24. String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
  25. URL localURL = new URL("http://localhost:8080/MyHttpServer/");
  26. URLConnection connection = localURL.openConnection();
  27. HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
  28. httpURLConnection.setDoOutput(true);
  29. httpURLConnection.setRequestMethod("POST");
  30. httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
  31. httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  32. httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
  33. OutputStream outputStream = null;
  34. OutputStreamWriter outputStreamWriter = null;
  35. InputStream inputStream = null;
  36. InputStreamReader inputStreamReader = null;
  37. BufferedReader reader = null;
  38. StringBuffer resultBuffer = new StringBuffer();
  39. String tempLine = null;
  40. try {
  41. outputStream = httpURLConnection.getOutputStream();
  42. outputStreamWriter = new OutputStreamWriter(outputStream);
  43. outputStreamWriter.write(parameterData.toString());
  44. outputStreamWriter.flush();
  45. if (httpURLConnection.getResponseCode() >= 300) {
  46. throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
  47. }
  48. inputStream = httpURLConnection.getInputStream();
  49. inputStreamReader = new InputStreamReader(inputStream);
  50. reader = new BufferedReader(inputStreamReader);
  51. while ((tempLine = reader.readLine()) != null) {
  52. resultBuffer.append(tempLine);
  53. }
  54. } finally {
  55. if (outputStreamWriter != null) {
  56. outputStreamWriter.close();
  57. }
  58. if (outputStream != null) {
  59. outputStream.close();
  60. }
  61. if (reader != null) {
  62. reader.close();
  63. }
  64. if (inputStreamReader != null) {
  65. inputStreamReader.close();
  66. }
  67. if (inputStream != null) {
  68. inputStream.close();
  69. }
  70. }
  71. return resultBuffer.toString();
  72. }
  73. }

运行结果:

It is ok!

3 对Get和Post进行封装

封装类:

  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. public class HttpRequestor {
  15. private String charset = "utf-8";
  16. private Integer connectTimeout = null;
  17. private Integer socketTimeout = null;
  18. private String proxyHost = null;
  19. private Integer proxyPort = null;
  20. /**
  21. * Do GET request
  22. * @param url
  23. * @return
  24. * @throws Exception
  25. * @throws IOException
  26. */
  27. public String doGet(String url) throws Exception {
  28. URL localURL = new URL(url);
  29. URLConnection connection = openConnection(localURL);
  30. HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
  31. httpURLConnection.setRequestProperty("Accept-Charset", charset);
  32. httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  33. InputStream inputStream = null;
  34. InputStreamReader inputStreamReader = null;
  35. BufferedReader reader = null;
  36. StringBuffer resultBuffer = new StringBuffer();
  37. String tempLine = null;
  38. if (httpURLConnection.getResponseCode() >= 300) {
  39. throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
  40. }
  41. try {
  42. inputStream = httpURLConnection.getInputStream();
  43. inputStreamReader = new InputStreamReader(inputStream);
  44. reader = new BufferedReader(inputStreamReader);
  45. while ((tempLine = reader.readLine()) != null) {
  46. resultBuffer.append(tempLine);
  47. }
  48. } finally {
  49. if (reader != null) {
  50. reader.close();
  51. }
  52. if (inputStreamReader != null) {
  53. inputStreamReader.close();
  54. }
  55. if (inputStream != null) {
  56. inputStream.close();
  57. }
  58. }
  59. return resultBuffer.toString();
  60. }
  61. /**
  62. * Do POST request
  63. * @param url
  64. * @param parameterMap
  65. * @return
  66. * @throws Exception
  67. */
  68. public String doPost(String url, Map parameterMap) throws Exception {
  69. /* Translate parameter map to parameter date string */
  70. StringBuffer parameterBuffer = new StringBuffer();
  71. if (parameterMap != null) {
  72. Iterator iterator = parameterMap.keySet().iterator();
  73. String key = null;
  74. String value = null;
  75. while (iterator.hasNext()) {
  76. key = (String)iterator.next();
  77. if (parameterMap.get(key) != null) {
  78. value = (String)parameterMap.get(key);
  79. } else {
  80. value = "";
  81. }
  82. parameterBuffer.append(key).append("=").append(value);
  83. if (iterator.hasNext()) {
  84. parameterBuffer.append("&");
  85. }
  86. }
  87. }
  88. System.out.println("POST parameter : " + parameterBuffer.toString());
  89. URL localURL = new URL(url);
  90. URLConnection connection = openConnection(localURL);
  91. HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
  92. httpURLConnection.setDoOutput(true);
  93. httpURLConnection.setRequestMethod("POST");
  94. httpURLConnection.setRequestProperty("Accept-Charset", charset);
  95. httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  96. httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
  97. OutputStream outputStream = null;
  98. OutputStreamWriter outputStreamWriter = null;
  99. InputStream inputStream = null;
  100. InputStreamReader inputStreamReader = null;
  101. BufferedReader reader = null;
  102. StringBuffer resultBuffer = new StringBuffer();
  103. String tempLine = null;
  104. try {
  105. outputStream = httpURLConnection.getOutputStream();
  106. outputStreamWriter = new OutputStreamWriter(outputStream);
  107. outputStreamWriter.write(parameterBuffer.toString());
  108. outputStreamWriter.flush();
  109. if (httpURLConnection.getResponseCode() >= 300) {
  110. throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
  111. }
  112. inputStream = httpURLConnection.getInputStream();
  113. inputStreamReader = new InputStreamReader(inputStream);
  114. reader = new BufferedReader(inputStreamReader);
  115. while ((tempLine = reader.readLine()) != null) {
  116. resultBuffer.append(tempLine);
  117. }
  118. } finally {
  119. if (outputStreamWriter != null) {
  120. outputStreamWriter.close();
  121. }
  122. if (outputStream != null) {
  123. outputStream.close();
  124. }
  125. if (reader != null) {
  126. reader.close();
  127. }
  128. if (inputStreamReader != null) {
  129. inputStreamReader.close();
  130. }
  131. if (inputStream != null) {
  132. inputStream.close();
  133. }
  134. }
  135. return resultBuffer.toString();
  136. }
  137. private URLConnection openConnection(URL localURL) throws IOException {
  138. URLConnection connection;
  139. if (proxyHost != null && proxyPort != null) {
  140. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
  141. connection = localURL.openConnection(proxy);
  142. } else {
  143. connection = localURL.openConnection();
  144. }
  145. return connection;
  146. }
  147. /**
  148. * Render request according setting
  149. * @param request
  150. */
  151. private void renderRequest(URLConnection connection) {
  152. if (connectTimeout != null) {
  153. connection.setConnectTimeout(connectTimeout);
  154. }
  155. if (socketTimeout != null) {
  156. connection.setReadTimeout(socketTimeout);
  157. }
  158. }
  159. /*
  160. * Getter & Setter
  161. */
  162. public Integer getConnectTimeout() {
  163. return connectTimeout;
  164. }
  165. public void setConnectTimeout(Integer connectTimeout) {
  166. this.connectTimeout = connectTimeout;
  167. }
  168. public Integer getSocketTimeout() {
  169. return socketTimeout;
  170. }
  171. public void setSocketTimeout(Integer socketTimeout) {
  172. this.socketTimeout = socketTimeout;
  173. }
  174. public String getProxyHost() {
  175. return proxyHost;
  176. }
  177. public void setProxyHost(String proxyHost) {
  178. this.proxyHost = proxyHost;
  179. }
  180. public Integer getProxyPort() {
  181. return proxyPort;
  182. }
  183. public void setProxyPort(Integer proxyPort) {
  184. this.proxyPort = proxyPort;
  185. }
  186. public String getCharset() {
  187. return charset;
  188. }
  189. public void setCharset(String charset) {
  190. this.charset = charset;
  191. }
  192. }

客户端测试代码:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class Call {
  4. public static void main(String[] args) throws Exception {
  5. /* Post Request */
  6. Map dataMap = new HashMap();
  7. dataMap.put("username", "Zheng");
  8. dataMap.put("blog", "IT");
  9. System.out.println(new HttpRequestor().doPost("http://localhost:8080/MyHttpServer/", dataMap));
  10. /* Get Request */
  11. System.out.println(new HttpRequestor().doGet("http://localhost:8080/MyHttpServer/"));
  12. }
  13. }

运行结果:

POST parameter : blog=IT&username=Zheng

It is ok!

It is ok!

Java笔记7:最简单的网络请求Demo的更多相关文章

  1. Xamarin.Android之封装个简单的网络请求类

    一.前言 回忆到上篇 <Xamarin.Android再体验之简单的登录Demo> 做登录时,用的是GET的请求,还用的是同步, 于是现在将其简单的改写,做了个简单的封装,包含基于Http ...

  2. Android 最早使用的简单的网络请求

    下面是最早从事android开发的时候写的网络请求的代码,简单高效,对于理解http请求有帮助.直接上代码,不用解释,因为非常简单. import java.io.BufferedReader; im ...

  3. iOS之ASIHttp简单的网络请求实现

    描述: ASIHttpRequest是应用第三方库的方法,利用代码快,减少代码量,提高效率 准备工作: 一.导入第三方库ASIHttpRequest 二.会报很多的错,原因有两个,一个是要导入Xcod ...

  4. 学习笔记TF028:实现简单卷积网络

    载入MNIST数据集.创建默认Interactive Session. 初始化函数,权重制造随机噪声打破完全对称.截断正态分布噪声,标准差设0.1.ReLU,偏置加小正值(0.1),避免死亡节点(de ...

  5. java编写的一段简单的网络爬虫demo代码

    功能: 从网站上下载附件,并从页面中提取页面文章内容 关于NIO 在大多数情况下,Java 应用程序并非真的受着 I/O 的束缚.操作系统并非不能快速传送数据,让 Java 有事可做:相反,是 JVM ...

  6. Xamarin 简单的网络请求

    //try            //{            //    var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(re ...

  7. python 学习笔记之手把手讲解如何使用原生的 urllib 发送网络请求

    urllib.urlopen(url[,data[,proxies]]) : https://docs.python.org/2/library/urllib.html python 中默认自带的网络 ...

  8. Android 网络请求详解

    我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的.如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient ...

  9. NSURLSession网络请求

    个人感觉在网上很难找到很简单的网络请求.或许是我才疏学浅 ,  所有就有了下面这一段 , 虽然都是代码 , 但是全有注释 . //1/获取文件访问路径 NSString *path=@"ht ...

随机推荐

  1. (七)计算G711语音的打包长度和RTP里timestamp的增长量

    如何计算G711语音等的打包长度和RTP里timestamp的增长量 一般对于不同的语音有不同的打包周期,而不同的打包周期又对应着不同的timestamp in RTP 那么是如何计算的呢,我们通过G ...

  2. 在oracle官网上,找到我们所需版本的jdk

    oracle的官网,因为都是英文,而且内容还特别多,经常的找不到历史版本的JDK. 特地,将找历史版本JDK的方法记录下来. 访问:http://www.oracle.com/technetwork/ ...

  3. pygame --- 可怜的小乌龟

    来于----@小甲鱼工作室 import pygame import sys from pygame.locals import * #初始化 pygame.init() size = width,h ...

  4. Selenium2+python自动化48-登录方法(参数化)【转载】

    前言 登录这个场景在写用例的时候经常会有,我们可以把登录封装成一个方法,然后把账号和密码参数化,这样以后用的登录的时候,只需调用这个方法就行了 一.登录方法 1.把输入账号.输入密码.点击登录按钮三个 ...

  5. BMP文件组成

    BMP文件组成 BMP文件由文件头.位图信息头.颜色信息和图形数据四部分组成. 如图: 位图文件头BITMAPFILEHEADER 位图信息头BITMAPINFOHEADER 调色板Palette 实 ...

  6. java javac 的区别

    cmd中,执行java命令与javac命令的区别: javac:是编译命令,将java源文件编译成.class字节码文件. 例如:javac hello.java 将生成hello.class文件 j ...

  7. 图解Javascript——执行上下文

    什么是执行上下文? 执行上下文(Execution Context)是ECMAScript规范中用来描述 JavaScript 代码执行的抽象概念,规定了当前代码执行的环境(当前执行代码片段中的变量. ...

  8. shell脚本学习(二)

    shell传递参数 shell脚本在执行是可以传递参数,脚本内获取参数的格式为:$n,n为一个数字,1为第一个参数,2为第二个参数,以此类推 其中,$0代表了要执行的文件名 实例: 代码如下: #!/ ...

  9. HDU 6330.Problem L. Visual Cube-模拟到上天-输出立方体 (2018 Multi-University Training Contest 3 1012)

    6330.Problem L. Visual Cube 这个题就是输出立方体.当时写完怎么都不过,后来输出b<c的情况,发现这里写挫了,判断失误.加了点东西就过了,mdzz... 代码: //1 ...

  10. 在小程序开发中使用 npm

    微信小程序在发布之初没有对 npm 的支持功能,这也是目前很多前端开发人员在熟悉了 npm 生态环境后,对微信小程序诟病的地方. 微信小程序在 2.2.1 版本后增加了对 npm 包加载的支持,使得小 ...