Java笔记7:最简单的网络请求Demo
一、服务器端
1 新建一个工程,建立一个名为MyRequest的工程。
2 FileàProject StructureàModulesà点击最右侧的“+”àLibraryàJava
找到Tomcat中的lib目录下的servlet-api.jar,添加进来
3 建立LoginServlet类,内容如下
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class LoginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public LoginServlet() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request, response);
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String username = request.getParameter("username");
- String blog = request.getParameter("blog");
- System.out.println(username);
- System.out.println(blog);
- response.setContentType("text/plain; charset=UTF-8");
- response.setCharacterEncoding("UTF-8");
- response.getWriter().write("It is ok!");
- }
- }
4 编译LoginServlet.java,得到LoginServlet.class
5 在Tomcat中的webapps中添加MyHttpServer\WEB-INF\classes,并把上一步生成的LoginServlet.class拷进来
6 在WEB-INF目录下建立web.xml文件,内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <display-name>OneHttpServer</display-name>
- <welcome-file-list>
- <welcome-file>LoginServlet</welcome-file>
- </welcome-file-list>
- <servlet>
- <description></description>
- <display-name>LoginServlet</display-name>
- <servlet-name>LoginServlet</servlet-name>
- <servlet-class>LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LoginServlet</servlet-name>
- <url-pattern>/LoginServlet</url-pattern>
- </servlet-mapping>
- </web-app>
7 执行Tomcat下的bin目录下的startup.bat来启动Tomcat
8 在浏览器中输入http://localhost:8080/MyHttpServer,若见到页面显示“It is ok!”则表示服务器端配置成功。
二、客户端
1 Get请求
在MyRequest工程新建HttpGetRequest类,内容如下:
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- public class HttpGetRequest {
- /**
- * Main
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- System.out.println(doGet());
- }
- /**
- * Get Request
- * @return
- * @throws Exception
- */
- public static String doGet() throws Exception {
- URL localURL = new URL("http://localhost:8080/MyHttpServer/");
- URLConnection connection = localURL.openConnection();
- HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
- httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
- httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
- StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
- if (httpURLConnection.getResponseCode() >= 300) {
- throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
- }
- try {
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(inputStreamReader);
- while ((tempLine = reader.readLine()) != null) {
- resultBuffer.append(tempLine);
- }
- } finally {
- if (reader != null) {
- reader.close();
- }
- if (inputStreamReader != null) {
- inputStreamReader.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- }
- return resultBuffer.toString();
- }
- }
运行结果:
It is ok!
2 Post请求
新建HttpPostRequest.java类,内容如下:
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- public class HttpPostRequest {
- /**
- * Main
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- System.out.println(doPost());
- }
- /**
- * Post Request
- * @return
- * @throws Exception
- */
- public static String doPost() throws Exception {
- String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
- URL localURL = new URL("http://localhost:8080/MyHttpServer/");
- URLConnection connection = localURL.openConnection();
- HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
- httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
- OutputStream outputStream = null;
- OutputStreamWriter outputStreamWriter = null;
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
- StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
- try {
- outputStream = httpURLConnection.getOutputStream();
- outputStreamWriter = new OutputStreamWriter(outputStream);
- outputStreamWriter.write(parameterData.toString());
- outputStreamWriter.flush();
- if (httpURLConnection.getResponseCode() >= 300) {
- throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
- }
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(inputStreamReader);
- while ((tempLine = reader.readLine()) != null) {
- resultBuffer.append(tempLine);
- }
- } finally {
- if (outputStreamWriter != null) {
- outputStreamWriter.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- if (reader != null) {
- reader.close();
- }
- if (inputStreamReader != null) {
- inputStreamReader.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- }
- return resultBuffer.toString();
- }
- }
运行结果:
It is ok!
3 对Get和Post进行封装
封装类:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.InetSocketAddress;
- import java.net.Proxy;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.Iterator;
- import java.util.Map;
- public class HttpRequestor {
- private String charset = "utf-8";
- private Integer connectTimeout = null;
- private Integer socketTimeout = null;
- private String proxyHost = null;
- private Integer proxyPort = null;
- /**
- * Do GET request
- * @param url
- * @return
- * @throws Exception
- * @throws IOException
- */
- public String doGet(String url) throws Exception {
- URL localURL = new URL(url);
- URLConnection connection = openConnection(localURL);
- HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
- httpURLConnection.setRequestProperty("Accept-Charset", charset);
- httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
- StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
- if (httpURLConnection.getResponseCode() >= 300) {
- throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
- }
- try {
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(inputStreamReader);
- while ((tempLine = reader.readLine()) != null) {
- resultBuffer.append(tempLine);
- }
- } finally {
- if (reader != null) {
- reader.close();
- }
- if (inputStreamReader != null) {
- inputStreamReader.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- }
- return resultBuffer.toString();
- }
- /**
- * Do POST request
- * @param url
- * @param parameterMap
- * @return
- * @throws Exception
- */
- public String doPost(String url, Map parameterMap) throws Exception {
- /* Translate parameter map to parameter date string */
- StringBuffer parameterBuffer = new StringBuffer();
- if (parameterMap != null) {
- Iterator iterator = parameterMap.keySet().iterator();
- String key = null;
- String value = null;
- while (iterator.hasNext()) {
- key = (String)iterator.next();
- if (parameterMap.get(key) != null) {
- value = (String)parameterMap.get(key);
- } else {
- value = "";
- }
- parameterBuffer.append(key).append("=").append(value);
- if (iterator.hasNext()) {
- parameterBuffer.append("&");
- }
- }
- }
- System.out.println("POST parameter : " + parameterBuffer.toString());
- URL localURL = new URL(url);
- URLConnection connection = openConnection(localURL);
- HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setRequestProperty("Accept-Charset", charset);
- httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
- OutputStream outputStream = null;
- OutputStreamWriter outputStreamWriter = null;
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
- StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
- try {
- outputStream = httpURLConnection.getOutputStream();
- outputStreamWriter = new OutputStreamWriter(outputStream);
- outputStreamWriter.write(parameterBuffer.toString());
- outputStreamWriter.flush();
- if (httpURLConnection.getResponseCode() >= 300) {
- throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
- }
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(inputStreamReader);
- while ((tempLine = reader.readLine()) != null) {
- resultBuffer.append(tempLine);
- }
- } finally {
- if (outputStreamWriter != null) {
- outputStreamWriter.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- if (reader != null) {
- reader.close();
- }
- if (inputStreamReader != null) {
- inputStreamReader.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
- }
- return resultBuffer.toString();
- }
- private URLConnection openConnection(URL localURL) throws IOException {
- URLConnection connection;
- if (proxyHost != null && proxyPort != null) {
- Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
- connection = localURL.openConnection(proxy);
- } else {
- connection = localURL.openConnection();
- }
- return connection;
- }
- /**
- * Render request according setting
- * @param request
- */
- private void renderRequest(URLConnection connection) {
- if (connectTimeout != null) {
- connection.setConnectTimeout(connectTimeout);
- }
- if (socketTimeout != null) {
- connection.setReadTimeout(socketTimeout);
- }
- }
- /*
- * Getter & Setter
- */
- public Integer getConnectTimeout() {
- return connectTimeout;
- }
- public void setConnectTimeout(Integer connectTimeout) {
- this.connectTimeout = connectTimeout;
- }
- public Integer getSocketTimeout() {
- return socketTimeout;
- }
- public void setSocketTimeout(Integer socketTimeout) {
- this.socketTimeout = socketTimeout;
- }
- public String getProxyHost() {
- return proxyHost;
- }
- public void setProxyHost(String proxyHost) {
- this.proxyHost = proxyHost;
- }
- public Integer getProxyPort() {
- return proxyPort;
- }
- public void setProxyPort(Integer proxyPort) {
- this.proxyPort = proxyPort;
- }
- public String getCharset() {
- return charset;
- }
- public void setCharset(String charset) {
- this.charset = charset;
- }
- }
客户端测试代码:
- import java.util.HashMap;
- import java.util.Map;
- public class Call {
- public static void main(String[] args) throws Exception {
- /* Post Request */
- Map dataMap = new HashMap();
- dataMap.put("username", "Zheng");
- dataMap.put("blog", "IT");
- System.out.println(new HttpRequestor().doPost("http://localhost:8080/MyHttpServer/", dataMap));
- /* Get Request */
- System.out.println(new HttpRequestor().doGet("http://localhost:8080/MyHttpServer/"));
- }
- }
运行结果:
POST parameter : blog=IT&username=Zheng
It is ok!
It is ok!
Java笔记7:最简单的网络请求Demo的更多相关文章
- Xamarin.Android之封装个简单的网络请求类
一.前言 回忆到上篇 <Xamarin.Android再体验之简单的登录Demo> 做登录时,用的是GET的请求,还用的是同步, 于是现在将其简单的改写,做了个简单的封装,包含基于Http ...
- Android 最早使用的简单的网络请求
下面是最早从事android开发的时候写的网络请求的代码,简单高效,对于理解http请求有帮助.直接上代码,不用解释,因为非常简单. import java.io.BufferedReader; im ...
- iOS之ASIHttp简单的网络请求实现
描述: ASIHttpRequest是应用第三方库的方法,利用代码快,减少代码量,提高效率 准备工作: 一.导入第三方库ASIHttpRequest 二.会报很多的错,原因有两个,一个是要导入Xcod ...
- 学习笔记TF028:实现简单卷积网络
载入MNIST数据集.创建默认Interactive Session. 初始化函数,权重制造随机噪声打破完全对称.截断正态分布噪声,标准差设0.1.ReLU,偏置加小正值(0.1),避免死亡节点(de ...
- java编写的一段简单的网络爬虫demo代码
功能: 从网站上下载附件,并从页面中提取页面文章内容 关于NIO 在大多数情况下,Java 应用程序并非真的受着 I/O 的束缚.操作系统并非不能快速传送数据,让 Java 有事可做:相反,是 JVM ...
- Xamarin 简单的网络请求
//try //{ // var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(re ...
- python 学习笔记之手把手讲解如何使用原生的 urllib 发送网络请求
urllib.urlopen(url[,data[,proxies]]) : https://docs.python.org/2/library/urllib.html python 中默认自带的网络 ...
- Android 网络请求详解
我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的.如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient ...
- NSURLSession网络请求
个人感觉在网上很难找到很简单的网络请求.或许是我才疏学浅 , 所有就有了下面这一段 , 虽然都是代码 , 但是全有注释 . //1/获取文件访问路径 NSString *path=@"ht ...
随机推荐
- 在css中设置图片的背景图,怎么设置图片纵向拉伸
css中设置背景图拉伸填充,在css2.1之前这个背景的长宽值是不能被修改的. 实际的结果是只能重复显示,可以使用repeat,repeat-x,repeat-y,no-repeat这些属性来控制背景 ...
- Java常见知识点(二)
21.常量池专门用于管理在编译时被确定并被保存在已编译的.class文件中的一些数据.它包括了关于类.方法.接口中的常量,还包括字符串常量. 22.String已经重写了Object的equals ...
- python中的yield生成器详解
#原创,转载请先联系 在学习生成器之前,必须先了解一下迭代器.因为生成器就是一种特殊的迭代器,而且生成器用起来更加优雅. 迭代器的详解可以参考我的另一篇博文:https://www.cnblogs.c ...
- python算法:约瑟夫问题
据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特後,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被人抓到,于是决定了一个自杀方式,41 ...
- Django基础之模板
Django模板系统 官方文档 常用语法 只需要记两种特殊符号: {{ }} 和 {% %} 变量相关的用{{ }},逻辑相关的用{% %}. 变量 {{ 变量名 }} 变量名由字母数字和下划线组成 ...
- Mysql的碎片查看与处理
-- 每张表的大小 参考网址:http://www.oschina.net/question/12_3673 -- DATA_FREE 大于零表示有碎片 -- 在我们的项目中,生产环境一律采用独立的表 ...
- Redis数据类型的常用API以及使用场景
一.通用命令 1.keys 遍历出所有的key 一般不在生产环境使用 2.dbsize key的总数 3.exists key 4.del key 删除指定key-value 5.expire k ...
- codeforces 671C
题意定义f(l,r)为去掉[l,r]部分后剩下的数任意两个数的最大公约数的最大值 现在求f(l,r)的和 由于每个数ai最大只有200000,因此我们穷举因子x,记录以其为因子的a[i]的i值并按i升 ...
- UVA 10341.Solve It-二分查找
二分查找 二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好:其缺点是要求待查表为有序表,且插入删除困难.因此,折半查找方法适用于不经常变动而查找频繁的有序列表.首先,假设表中元素是按升序 ...
- UESTC 1599.wtmsb-STL(priority_queue)
wtmsb Time Limit: 1000/100MS (Java/Others) Memory Limit: 131072/131072KB (Java/Others) 这天,AutSky_Jad ...