一般在网站搭建中servlet只需处理post,get请求便足已。本篇注重使用javaweb编写restful风格api,在servlet中对四种常用请求进行处理。
在api中对于一个请求要做的通常是提取header参数,提取携带数据(post,put)。在这里已post为例来说明用法。
下面是发起的post请求,用python(很简单)写的,该请求既有自定义header参数Bearer,也有携带数据bodys里的内容
import json import requests taken='YWMtoWBEBAFOEeei0SdHniRB6QAAAAAAAAAAAAAAAAAAjwAU4R56atn3HZQyagAgMAAAFanGEFTABPGgAqPOaU00kjW851AIpsKCuT8jAG1PqHyBpY6y5vOgk1zg' headers = {'Accept': 'application/json','Content-Type':'application/json','Authorization':'Bearer '+taken} bodys={'username':'test5','password':'123456'} url='http://localhost:8080/xiaoyanAPI' response=requests.post(url,data=json.dumps(bodys),headers=headers) print response.text
下面是处理post请求代码
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 //打印某一个header 3 System.out.println(request.getHeader("Authorization")); 4 System.out.println(); 5 //获取header参数名,并打印出内容 6 Enumeration<String> s=request.getHeaderNames(); 7 String str; 8 while((str=s.nextElement())!=null) 9 System.out.println(request.getHeader(str)); 10 System.out.println(); 11 //获取post携带数据流 12 String acceptjson; 13 try { 14 BufferedReader br = new BufferedReader(new InputStreamReader( (ServletInputStream) request.getInputStream(), "utf-8")); 15 StringBuffer sb = new StringBuffer(""); 16 String temp; 17 while ((temp = br.readLine()) != null) { 18 sb.append(temp); 19 } 20 br.close(); 21 acceptjson = sb.toString(); 22 System.out.print(acceptjson); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 }
其他三种请求处理方式类似。