request

本文详细介绍了HTTP请求中的常用方法,如GET、POST,如何获取请求头、请求数据及实现请求转发与页面包含的技术细节。同时,讨论了解决中文乱码问题的方法,并展示了在Web开发中使用request进行数据传递的多种应用场景。

request常用方法:

Servlet代码:

public class RequestDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println(request.getRequestURI());
		System.out.println(request.getRequestURL());
		//返回请求行参数http://localhost:8080/day06/servlet/RequestDemo1?username=aaa
		System.out.println(request.getQueryString());
		
		System.out.println("=====================");
		
		System.out.println(request.getRemoteAddr());
		System.out.println(request.getRemoteHost());
		
		System.out.println(request.getRemotePort());
		
		System.out.println(request.getMethod());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

request获取请求头:

Servlet代码:
//获取请求头相关的方法
	private void test1(HttpServletRequest request) {
		//如果有多个该头,getHeader只能获得第一个头的值
		String headValue = request.getHeader("Accept-Encoding");
		System.out.println(headValue);
		
		System.out.println("=======================");
		//getHeaders可以获得所有同名该头的值
		Enumeration e = request.getHeaders("Accept-Encoding");
		while(e.hasMoreElements()){
			String value = (String)e.nextElement();
			System.out.println(value);
		}
		
		System.out.println("=======================");
		//getHeaderNames可以获得所有头的名字
		e = request.getHeaderNames();
		while(e.hasMoreElements()){
			String name = (String)e.nextElement();
			String value = request.getHeader(name);
			System.out.println(value);
		}
	}

request获取请求数据:
html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>带数据给RequestDemo2</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  </head>
  
  <body>
    <!-- 向服务器提交数据的两种方式 -->
    <a href="/day06/servlet/RequestDemo2?username=xxx">点点</a>
    
    <form action="/day06/servlet/RequestDemo2" method="post">
    	用户名1:<input type="text" name="username"/></br>
    	用户名2:<input type="text" name="username"/></br>
    	密码:<input type="text" name="password"/></br>
    	<input type="submit" value="提交"/></br>
    </form>
    
  </body>
</html>

Servlet代码:

//User对象,用于封装提交的数据
public class User {
	private String username[];
	private String password[];
	public String[] getUsername() {
		return username;
	}
	public void setUsername(String[] username) {
		this.username = username;
	}
	public String[] getPassword() {
		return password;
	}
	public void setPassword(String[] password) {
		this.password = password;
	}
	
}
//获取请求数据
	//获取请求数据时一般来说都要先检查再使用
	//防止用户吃饱了撑的不输入数据或者只输入空格就提交,报异常
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("==========获取数据方式1===========");
		//常用:获取指定参数的值
		String value = request.getParameter("username");
		if(value!=null&&!value.trim().equals("")){
			System.out.println(value);
		}
		
		System.out.println("==========获取数据方式2===========");
		Enumeration e =request.getParameterNames();
		while(e.hasMoreElements()){
			String name = (String)e.nextElement();//username password
			value = request.getParameter(name);
			if(value!=null&&!value.trim().equals("")){
				System.out.println(name+" = "+value);
			}
		}
		
		System.out.println("==========获取数据方式3===========");
		//getParameterValues得到所有同名参数的值
		String[] values = request.getParameterValues("username");
		for(int i =0;values!=null&&i<values.length;i++){
			System.out.println(values[i]);
		}
		//增强for循环
//		for(String v : values){
//			System.out.println(v);
//		}
		
		System.out.println("==========获取数据方式4===========");
		//常用:将数据封装到对象(user)中去,导入beanutils和logging包
		Map<String,String[]> map = request.getParameterMap();
		User user = new User();
		try {
			BeanUtils.populate(user, map);	//username String[] 用map集合的数据填充bean
			
			//bean的拷贝
			//把表单数据封装到formbean对象中,再将formbean拷贝到user对象
			//拷贝想成功,属性值必须是String或Buffer基本类型
//			BeanUtils.copyProperties(user, formbean); 
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println((String)user.getUsername()[1]);
		
		System.out.println("==========获取数据方式5===========");
		//实际开发不常用,一般用于文件上传
		InputStream in = request.getInputStream();
		int len = 0;
		byte buffer[] = new byte[1024];
		while((len=in.read(buffer))>0){
			System.out.println(new String(buffer,0,len));
		}
		
	}

request常见应用:



通过表单获取客户机数据:

html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>传数据给requestDemo3</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
  </head>
  
  <body>
  	<!-- url后面如果跟了中文数据,要编码后再提交 -->
    <form action="/day06/servlet/RequestDemo3" method="post">
    	用户名:<input type="text" name="username"/></br>
    	密码:<input type="password" name="password"/></br>
    	性别:
    		<input type="radio" name="gender" value="male"/>男
    		<input type="radio" name="gender" value="female"/>女<br/>
    	
    	所在地:
    		<select name="city">
    			<option value="beijing">北京</option>
    			<option value="shanghai">上海</option>
    			<option value="cs">长沙</option>
    		</select>
    		</br>
    	爱好:
    		<input type="checkbox" name="likes" value="sing"/>唱歌
    		<input type="checkbox" name="likes" value="dance"/>跳舞
    		<input type="checkbox" name="likes" value="basketball"/>篮球
    		<input type="checkbox" name="likes" value="football"/>足球
    		</br>
    	备注:<textarea rows="6" cols="60" name="description"></textarea></br>	
    	
    	大头照:<input type="file" name="image"/></br>
    	
    	<input type="hidden" name="id" value="12345"/>
    	
    	<input type="submit" value="提交"/></br>
    </form>
  </body>
</html>
Servlet代码:

public class RequestDemo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println(request.getParameter("username"));
		System.out.println(request.getParameter("password"));
		System.out.println(request.getParameter("gender"));
		System.out.println(request.getParameter("city"));
		String likes[] = request.getParameterValues("likes");
		for(int i = 0;likes!=null&&i<likes.length;i++){
			System.out.println(likes[i]);
		}
		System.out.println(request.getParameter("description"));
		System.out.println(request.getParameter("id"));
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
request中文乱码问题:
html代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>中文乱码</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
  </head>
  
  <body>
    <form action="/day06/servlet/RequestDemo4" method="post">
    	用户名:<input type="text" name="username"/></br>
    	<input type="submit" value="提交"/></br>
    </form>
    
    <form action="/day06/servlet/RequestDemo4" method="get">
    	用户名:<input type="text" name="username"/></br>
    	<input type="submit" value="提交"/></br>
    </form>
    
    <!-- 超链接提交的中文,服务器想不乱码,也只能手工处理,因为超链接也是get提交 -->
     <a href="/day06/servlet/RequestDemo4?username=中国">点点</a>
  </body>
</html>

Servlet代码:

public class RequestDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		test3(request,response);
	}
	
	//测试题
	private void test3(HttpServletRequest request,HttpServletResponse response)
			throws IOException {
		
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		
		response.setCharacterEncoding("gb2312");
		response.setHeader("Content-Type", "text/html;charset=gb2312");
		response.getWriter().write(username);
	}

	//解决post提交的乱码
	private void test2(HttpServletRequest request)
			throws UnsupportedEncodingException {
		
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		System.out.println(username);
	}
	
	//解决get提交的乱码(手工处理)
	private void test1(HttpServletRequest request)
			throws UnsupportedEncodingException {
		
		String username = request.getParameter("username");
		username = new String(username.getBytes("iso8859-1"),"UTF-8");
		System.out.println(username);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
request实现请求转发:
Servlet代码:

//请求转发,以及使用request域对象把数据带给转发资源
//请求转发的特点:
//1.客户端只发出一次请求,而服务器端有多个资源调用
//2.客户端浏览器地址栏没有变化
public class RequestDemo5 extends HttpServlet {

	//mvc	(m model(javabean) v view(jsp) c controller(servlet)	) 
	//controller(servlet)收到请求产生数据,使用model(javabean)封装,再把javabean存到request域里面带给view(jsp),有jsp取出数据输出
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String data = "aaaaaa";
		
		//不同请求用不同的request域,所以不会覆盖
		request.setAttribute("data", data);
		
		//以前用ServletContext把数据转发到目标页面,但是现在不这样用,以免转发过程中,另一个请求覆盖前一个请求的数据
//		this.getServletContext().setAttribute("data", data);
		
		//request也可以实现转发
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'message.jsp' starting page</title>
  </head>
  
  <body>
  
  	<!-- 自动从四个域里面找到data并输出,jsp不要出现java代码 -->
  	${data }
  
  	<%
  		//和上边jsp代码一样效果
  		String data = (String)request.getAttribute("data");
  		out.write(data);
  	 %>

  </body>
</html>
请求转发的细节:

Servlet代码:

//forward的细节,以下代码会抛异常(forward之前,若有内容已经发送到了客户端,则报异常)
public class RequestDemo6 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String data = "aaaaaa";
		
		PrintWriter writer = response.getWriter();
		writer.write(data);//数据写到response里
		writer.close();//关闭流后,则数据真正从response写到客户端
		
		if(true){
			request.getRequestDispatcher("/index.jsp").forward(request, response);//把数据转发到jsp再发送给客户端,也一样属于此异常
			return;//所以跳转后要return不执行下面转发语句,否则也会报异常
		}
		
		//以下转发会导致:java.lang.IllegalStateException:Cannot forward after response has been committed
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

//forward细节:forward时,会清空response中的数据
public class RequestDemo7 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String data = "aaaaaa";
		response.getWriter().write(data);
		
		//forward跳转之前会把response中的数据清空,所以看不到aaaaaa
		request.getRequestDispatcher("/index.jsp").forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

request实现页面包含:

head.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

    head<br/>

foot.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

   foot<br/>
Servlet代码:
//用include实现页面包含(被包含页面不要出现全局架构标签)
public class RequestDemo8 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.getRequestDispatcher("/public/head.jsp").include(request, response);
		
		response.getWriter().write("hahahaha<br/>");
		
		request.getRequestDispatcher("/public/foot.jsp").include(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


web工程中各类地址的写法:

Servlet代码:

//web工程中各类地址的写法:
//所有地址以"/"开头,
//若是给服务器用的,"/"就代表当前web应用
//若是给浏览器用的,"/"就代表网站
public class ServletDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//1.
		request.getRequestDispatcher("/form1.html").forward(request, response);
		
		//2.
		response.sendRedirect("/day06/form1.html");
		
		//3.
		this.getServletContext().getRealPath("/form1.html");
		
		//4.
		this.getServletContext().getResourceAsStream("/public/foot.jsp");
		
		//5.
		/*
		   <a href="/day06/form1.html">点点</a>
		 * 
		   <form action="/day06/form1.html">
		   
		   </form>
		 */
		
		//6.
		response.setHeader("refresh", "3;url='/day06/form1.html'");
		
		/*
		  c:\\	硬盘下路径用\\
		  http://	浏览器网址用//
		
		*/
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

利用referer防盗链:
首页index.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
  	<br/>看广告<br/>
  	
    <a href="/day06/servlet/RequestDemo9">看凤姐</a>
  </body>
</html>

Servlet代码:

//假设资源链接为http://localhost:8080/day06/servlet/RequsetDemo9
//防盗链
public class RequestDemo9 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String referer = request.getHeader("referer"); //获取客户机是从哪个资源访问服务器的
		
		if(referer==null||!referer.startsWith("http://localhost")){//如果客户机不是从首页访问资源的
			response.setStatus(302);
			response.setHeader("Location", "/day06/index.jsp");
			return;	//用return不必用else
		}
		
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		String data = "凤姐日记";
		response.getWriter().write(data);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


 

<think>好的,用户想下载与request相关的资源或库,具体是request库或者请求相关的工具。我需要根据提供的引用内容来解答这个问题。首先,我要看看用户提供的引用中有哪些相关的信息。 引用[1]提到安装request库的命令是`go get -u github.com/mozillazg/request`,看起来是Go语言的库。引用[2]和引用[4]分别提到了axios和react-request,这两个是JavaScript的库。引用[3]则是一个Mock-Request项目,用于模拟HTTP请求,可能也是JavaScript相关的。 用户的问题是关于下载request库或相关工具,所以需要分语言来回答。首先,确认用户使用的编程语言。不过用户没有明确说明,可能需要覆盖不同语言的情况。 对于Go语言的request库,引用[1]提供了安装命令,直接使用go get即可。对于JavaScript,常见的请求库如axios,可以通过npm安装。引用[2]提到安装axios,命令是`npm install axios`,而引用[4]的react-request可能需要使用npm或yarn安装。引用[3]的Mock-Request项目,可以通过GitCode的链接克隆或者下载。 此外,可能还需要补充Python的requests库,虽然用户提供的引用中没有提到,但这是Python中常用的请求库,安装命令是`pip install requests`。不过根据引用内容,用户提供的资料中没有这个信息,但根据常见知识,可能需要补充,但需注意是否超出引用范围。不过用户问题中的引用[1]是Go,引用[2][3][4]是JavaScript相关,所以可能不需要提到Python的requests。 不过用户的问题中引用的内容可能不够全面,需要根据给出的引用回答。因此,应该按照提供的四个引用来组织回答。Go的request库安装,JavaScript的axios和react-request,以及Mock-Request的模拟工具。 需要将每个引用对应的安装方式分点说明,语言清晰,结构明确。同时,生成相关问题,可能涉及各语言的不同库,或者不同用途的工具,比如模拟请求、React专用库等。 确保回答符合系统级指令,比如使用正确的中文,数学公式格式,但这里可能用不上数学公式。同时,在末尾添加相关问题,并正确引用标记。 现在组织回答: 首先分点说明不同语言和工具的安装方法: 1. Go语言的request库:引用[1]的命令。 2. JavaScript的axios:引用[2]中提到,安装命令是npm install axios。 3. Mock-Request:引用[3]中的GitCode链接,可以通过git克隆或下载。 4. React的react-request:引用[4],使用npm或yarn安装。 然后生成相关问题,比如不同语言的库如何选择,如何模拟请求,React中的请求处理等。</think>### 如何下载 request 库或请求相关工具 根据不同的编程语言和应用场景,以下是几种常见请求库的安装方法: --- #### 1. **Go语言的Request库** 引用[1]提供了Go语言的安装方式: ```bash go get -u github.com/mozillazg/request ``` 此命令会从GitHub仓库下载并安装`request`库,适用于需要HTTP客户端功能的Go项目[^1]。 --- #### 2. **JavaScript的Axios库** 引用[2]提到Axios是常用的HTTP请求工具,安装命令为: ```bash npm install axios ``` Axios适用于浏览器和Node.js环境,支持Promise API,适合前端项目或全栈开发[^2]。 --- #### 3. **Mock-Request(HTTP请求模拟工具)** 引用[3]推荐了Mock-Request项目,可通过GitCode克隆或下载: ```bash git clone https://gitcode.com/gh_mirrors/mo/mock-request ``` 该工具用于模拟HTTP请求,适合测试接口或开发环境调试[^3]。 --- #### 4. **React专用请求库:react-request** 引用[4]介绍了`react-request`,安装命令为: ```bash npm install react-request # 或使用yarn yarn add react-request ``` 此库专为React设计,简化了组件内网络请求的逻辑[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值