1.GET请求解释及语法格式
:
网络请求默认是get
网络请求有很多种:GET查 POST改 PUT增 DELETE删 HEAD
在平时开发中主要用的 是 get 和 post.
get 获得数据 (获取用户信息)
get 请求是没有长度限制的,真正的长度限制是浏览器做的,限制长度一般2k
get 请求是有缓存的,get 有幂等的算法
请求参数暴露在url里
get请求参数格式:
?后是请求参数
参数名 = 参数值
& 连接两个参数的
POST请求解释及语法格式
:
get请求参数格式:
?后是请求参数
参数名 = 参数值
& 连接两个参数的
post 添加,修改数据 (上传或修改用户信息)
post 请求是没有缓存的
post 也没有长度限制,一般控制2M以内
post 请求参数不会暴漏在外面 ,不会暴漏敏感信息
请求是有:请求头header,请求体boby(post参数是放在请求体里的)
GET请求代码
NSString *userName = @"haha"; NSString *password = @"123"; NSString *urlString = @"http://192.168.1.68/login.php"; //防止请求体中含有中文 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //?号是请求参数 注意username和password一定要和你的php页面的登录id相同 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?username=%@&password=%@",urlString,userName,password]]; //cachePolicy 缓存策略 0表示自动缓存 timeoutInterval: 默认请求时间60s,通常设置为10-30秒之间 NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:0]; // response是服务器返回信息: 里面有所用时间,服务器的型号等..... [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",string); }]; POST请求代码 NSString *userName = @"haha"; NSString *password = @"123"; NSString *urlString = @"http://192.168.1.68/login.php"; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlString]; //可变请求,因为是post请求所以要用NSMutableURLRequest NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10]; requst.HTTPMethod = @"POST"; NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@",userName,password]; //POST请求不写这个会访问失败-直接显示非法请求 requst.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",string); }];
2.通过设置响应头来实现下载功能
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a href="download?filename=1366768.jpg">下载图片</a> <a href="download?filename=1366.jpg">下载图片</a> <a href="download?filename=你好.txt">下载中文名称文档</a> </body> </html>
public class DownLoadServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); File f = new File(this.getServletContext().getRealPath("download/"+filename));//获取服务器资源 if(f.exists()) {//解决文件名中文问题 String agent = request.getHeader("user-agent"); if (agent.contains("MSIE")) { // IE浏览器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+", " "); } else if (agent.contains("Firefox")) { // 火狐浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?="; } else { // 其它浏览器 filename = URLEncoder.encode(filename, "utf-8"); } response.setContentType(this.getServletContext().getMimeType(f.getPath()));//设置页面文件类型 response.setHeader("Content-Disposition", "attachment;filename="+filename);//以附件方式打开文件 ServletOutputStream sos = response.getOutputStream(); FileInputStream fis = new FileInputStream(f); int len = 0; byte[] b = new byte[1024]; while((len=fis.read(b))!=-1) { sos.write(b,0,len); } fis.close(); }else { response.setContentType("text/html;charset=utf-8");//解决响应中文问题 response.getWriter().println("<h2 style='color:red;'>文件不存在!</h2>"); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3.验证码生成
public class CheckImgServlet extends HttpServlet { // 集合中保存所有成语 private List<String> words = new ArrayList<String>(); @Override public void init() throws ServletException { // 初始化阶段,读取new_words.txt // web工程中读取 文件,必须使用绝对磁盘路径 String path = getServletContext().getRealPath("/WEB-INF/new_words.txt"); try { BufferedReader reader = new BufferedReader(new FileReader(path)); String line; while ((line = reader.readLine()) != null) { words.add(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 禁止缓存 // response.setHeader("Cache-Control", "no-cache"); // response.setHeader("Pragma", "no-cache"); // response.setDateHeader("Expires", -1); int width = 120; int height = 30; // 步骤一 绘制一张内存中图片 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 步骤二 图片绘制背景颜色 ---通过绘图对象 Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔 // 绘制任何图形之前 都必须指定一个颜色 graphics.setColor(getRandColor(200, 250)); graphics.fillRect(0, 0, width, height); // 步骤三 绘制边框 graphics.setColor(Color.WHITE); graphics.drawRect(0, 0, width - 1, height - 1); // 步骤四 四个随机数字 Graphics2D graphics2d = (Graphics2D) graphics; // 设置输出字体 graphics2d.setFont(new Font("宋体", Font.BOLD, 18)); Random random = new Random();// 生成随机数 int index = random.nextInt(words.size()); String word = words.get(index);// 获得成语 // 定义x坐标 int x = 10; for (int i = 0; i < word.length(); i++) { // 随机颜色 graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); // 旋转 -30 --- 30度 int jiaodu = random.nextInt(60) - 30; // 换算弧度 double theta = jiaodu * Math.PI / 180; // 获得字母数字 char c = word.charAt(i); // 将c 输出到图片 graphics2d.rotate(theta, x, 20); graphics2d.drawString(String.valueOf(c), x, 20); graphics2d.rotate(-theta, x, 20); x += 30; } // 将验证码内容保存session request.getSession().setAttribute("checkcode_session", word); // 步骤五 绘制干扰线 graphics.setColor(getRandColor(160, 200)); int x1; int x2; int y1; int y2; for (int i = 0; i < 30; i++) { x1 = random.nextInt(width); x2 = random.nextInt(12); y1 = random.nextInt(height); y2 = random.nextInt(12); graphics.drawLine(x1, y1, x1 + x2, x2 + y2); } // 将上面图片输出到浏览器 ImageIO graphics.dispose();// 释放资源 //将图片写到response.getOutputStream()中 ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * 取其某一范围的color * * @param fc * int 范围参数1 * @param bc * int 范围参数2 * @return Color */ private Color getRandColor(int fc, int bc) { // 取其随机颜色 Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }