转自:http://www.cnblogs.com/edisonfeng/p/3830224.html

一、服务端

  1、主要结构:

   

  2、主要代码:

    1)web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name><!--lsdkalskdfjasdkfj-->
<servlet-class>com.wiscom.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

    2)LoginServlet.java

package com.wiscom.servlet;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8");//设置参数解码类型,必须和页面中一致
String sName=request.getParameter("name");
String sPassword=request.getParameter("psw"); PrintWriter out = response.getWriter();
if(sName.equals("admin")&&sPassword.equals("admin")){
out.print(sName+",您已成功登陆!!");
}else{
out.print(sName+",用户名密码有误!!");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
this.doGet(request, response);
}
}

二、客户端

  1、头文件:NetCenter.h

#import <Foundation/Foundation.h>

@interface NetCenter : NSObject

@property(nonatomic,retain) NSMutableData *receiveData;

@property(nonatomic,assign)int dataPackSerialNo;

- (void)httpGetSyn;

- (void)httpPostSyn;

- (void)httpGetNoSyn;

- (void)httpPostNoSyn;

@end

  2、实现文件:NetCenter.m

#import "NetCenter.h"

@implementation NetCenter

@synthesize receiveData=_receiveData;
@synthesize dataPackSerialNo=_dataPackSerialNo; - (void)httpGetSyn
{
NSLog(@"httpGetSyn..."); /*
NSString *urlString =url;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSMutableString *result = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"The result string is :%@",result);
*/
//第一步,创建URL
NSURL *url = [NSURL URLWithString:@"http://10.0.0.96:8080/app_server/LoginServlet?name=admin&psw=admin"]; //第二步,通过URL创建网络请求
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)
/*
其中缓存协议是个枚举类型包含:
NSURLRequestUseProtocolCachePolicy(基础策略)
NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)
NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
*/
//第三步,连接服务器
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); } - (void)httpPostSyn
{
NSLog(@"httpPostSyn..."); //第一步,创建URL
NSURL *url = [NSURL URLWithString:@"http://10.0.0.96:8080/app_server/LoginServlet"]; //第二步,创建请求
NSString *postStr = [[NSString alloc] initWithFormat:@"name=%@&psw=%@",@"admin",@"admin"];
NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
[request setHTTPBody:postData];//设置参数 //第三步,连接服务器
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *backStr = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding]; NSLog(@"%@",backStr);
} - (void)httpGetNoSyn
{
NSLog(@"httpGetNoSyn..."); //第一步,创建url
NSURL *url = [NSURL URLWithString:@"http://10.0.0.96:8080/app_server/LoginServlet?name=admin&psw=admin"]; //第二步,创建请求
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; //第三步,连接服务器
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; } - (void)httpPostNoSyn
{
NSLog(@"httpPostNoSyn..."); //第一步,创建url
NSURL *url = [NSURL URLWithString:@"http://10.0.0.96:8080/app_server/LoginServlet"]; //第二步,创建请求
NSString *postStr = [[NSString alloc] initWithFormat:@"name=%@&psw=%@",@"admin",@"admin"];
NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData]; //第三步,连接服务器
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
} /*************5、异步请求的代理方法[start]****************/ //接收到服务器回应的时候调用此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSLog(@"%@",[res allHeaderFields]);
self.receiveData = [NSMutableData data];//数据存储对象的的初始化
self.dataPackSerialNo=0;
NSLog(@"收到服务器回应。。。");
} //接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"收到服务器传回的数据包,数据包序号:%d",self.dataPackSerialNo);
[self.receiveData appendData:data];
self.dataPackSerialNo+=1;
} //数据传完之后调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"数据传输完成,输出所有数据结果。。。");
NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
NSLog(@"%@",receiveStr);
} //网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
-(void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"网络请求出错:%@",[error localizedDescription]);
} /*************5、异步请求的代理方法[end]****************/ @end

  3、调用

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; NetCenter *netCenter=[[NetCenter alloc]init]; /*****************同步请求****************/
//[netCenter httpGetSyn];
//[netCenter httpPostSyn]; /*****************异步请求****************/
//[netCenter httpGetNoSyn];
[netCenter httpPostNoSyn]; self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}  

三、测试

  1、同步get

  

  2、同步post

  

  3、异步get

  

  4、异步post

  

三、扩展

  1、http和https

    http://www.cnblogs.com/stan0714/archive/2012/03/21/2409872.html

  2、ios网络编程理论与实例

    http://blog.csdn.net/hgy2011/article/details/8676084

ios http 同步异步请求处理的更多相关文章

  1. iOS多线程——同步异步串行并行

    串行并行异步同步的概念很容易让人混淆,关于这几个概念我在第一篇GCD中有解释,但是还不够清晰,所以这里重写一篇博客专门对这几个概念进行区分: 先说一下队列和任务: (1)队列分为串行和并行,任务的执行 ...

  2. iOS:转载:同步、异步、并行、串行的详解

    理解 iOS 开发中 GCD 相关的同步(synchronization)\ 异步(asynchronization),串行(serial)\ 并行(concurrency)概念 2014年11月21 ...

  3. 【iOS开发-91】GCD的同步异步串行并行、NSOperation和NSOperationQueue一级用dispatch_once实现单例

    (1)GCD实现的同步异步.串行并行. --同步sync应用场景:用户登录,利用堵塞 --串行异步应用场景:下载等耗时间的任务 /** * 由于是异步.所以开通了子线程.可是由于是串行队列,所以仅仅须 ...

  4. iOS 多线程的简单理解(1) 方式 :同步 异步

    最近遇到特别糟糕的面试,过程中提到多次对多线程的处理问题,并没有很好的给予答复和解决,所以在这里做个简单的备案: 期望能更加了解和熟练使用 多线程技术: 下面都是自己的总结,如果存在不对的,或者不足, ...

  5. 【测试】Gunicorn , uWSGI同步异步测试以及应用场景总结

    最近使用uwsgi出了一些问题,于是测试下Gunicorn测试对比下 环境 一颗cpu 1g内存 Centos系统 Django作为后端应用,Gunicorn默认模式和异步模式,响应基本是无阻塞类型 ...

  6. .Net Core WebAPI 基于Task的同步&异步编程快速入门

    .Net Core WebAPI 基于Task的同步&异步编程快速入门 Task.Result async & await 总结 并行任务(Task)以及基于Task的异步编程(asy ...

  7. AJAX请求详解 同步异步 GET和POST

    AJAX请求详解 同步异步 GET和POST 上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介绍了AJAX的概念和基本使用,附有一个小例子,下面 ...

  8. 同步异步,阻塞非阻塞 和nginx的IO模型

    同步与异步 同步和异步关注的是消息通信机制 (synchronous communication/ asynchronous communication).所谓同步,就是在发出一个*调用*时,在没有得 ...

  9. 阻塞非阻塞,同步异步四种I/O方式

    举一个去书店买书的例子吧: (同步)阻塞: 你去书店买书,到柜台告诉店员,需要买一本APUE,然后一直在柜台等.(阻塞) 店员拿到书以后交给你. (同步)非阻塞: 你去书店买书,到柜台告诉店员A,需要 ...

随机推荐

  1. LeetCode->链表反转

    这是一个很基础的题目.今天处理了一下,不论是以双指针迭代.递归等方法,都能处理,但是也使这个题目更为典型. 剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn. ...

  2. [atAGC034F]RNG and XOR

    令$N=2^{n}$先将$\forall 0\le i<N,a_{i}$除以$\sum_{i=0}^{N-1}a_{i}$,即变为概率 令$f_{i}$表示$i$的答案(第一次变成$i$的期望步 ...

  3. RestSharp使用说明

    翻译自:https://github.com/restsharp/RestSharp/wiki,转载请注明. 一.新手入门 如果只有少量一次性请求需要封装为API,则可以如下使用RestSharp : ...

  4. Linux——防火墙、SELinux规则

    一.Firewalld防火墙规则 防火墙的作用:放行或者阻拦某些服务.端口 1.防火墙的简单操作 # 1.查看防火墙状态 systemctl status firewalld # 2.关闭防火墙 sy ...

  5. Codeforces 1466G - Song of the Sirens(哈希)

    Codeforces 题面传送门 & 洛谷题面传送门 事实证明,有的难度评分不算很高.涉及的知识点不算很难的题目也能出得非常神仙 首先考虑如何暴力求答案.注意到一个文本串 \(T\) 在 \( ...

  6. CF932F Escape Through Leaf

    CF932F Escape Through Leaf 首先, $ O(n^2) $ dp 是很显然的,方程长这样: \[dp[u] = min\{dp[v] + a_u\times b_v\} \] ...

  7. Codeforces 446D - DZY Loves Games(高斯消元+期望 DP+矩阵快速幂)

    Codeforces 题目传送门 & 洛谷题目传送门 神仙题,%%% 首先考虑所有格子都是陷阱格的情况,那显然就是一个矩阵快速幂,具体来说,设 \(f_{i,j}\) 表示走了 \(i\) 步 ...

  8. Python基础之字典内置方法

    目录 1. 字典 1.1 字典的作用 1.2 创建和使用字典 1.2.1 dict类 1.2.2 基本的字典操作 1.2.3 字典方法 1. 字典 映射:可以通过名称来访问其各个值的数据结构. 字典是 ...

  9. linux常用目录和文件解析

    1. 一级目录 /dev 设备目录 /etc 系统配置及服务配置文件.启动命令的目录 /proc 显示内核及进程信息的虚拟文件系统 /tmp 临时文件目录 /home 普通用户家目录 /root 超级 ...

  10. GeckoDriver的安装和使用

    GeckoDriver用于驱动Firefox,在这之前请确保已经正确安装好了Firefox浏览器并可以正常运行. 一.GeckoDriver的安装 GitHub:https://github.com/ ...