码迷,mamicode.com
首页 > 移动开发 > 详细

ios http 同步异步请求处理

时间:2014-12-15 15:10:28      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

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

一、服务端

  1、主要结构:

   bubuko.com,布布扣 

  2、主要代码:

    1)web.xml

bubuko.com,布布扣
<?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>
bubuko.com,布布扣

    2)LoginServlet.java

bubuko.com,布布扣
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);
  }
}
bubuko.com,布布扣

二、客户端

  1、头文件:NetCenter.h

bubuko.com,布布扣
#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
bubuko.com,布布扣

  2、实现文件:NetCenter.m

bubuko.com,布布扣
#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
bubuko.com,布布扣

  3、调用

bubuko.com,布布扣
- (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;
}  
bubuko.com,布布扣

三、测试

  1、同步get

  bubuko.com,布布扣

  2、同步post

  bubuko.com,布布扣

  3、异步get

  bubuko.com,布布扣

  4、异步post

  bubuko.com,布布扣

三、扩展

  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 同步异步请求处理

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://www.cnblogs.com/stephen-init/p/4164803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!