ios中的http:get,post,同步,非同步

来源:http://www.cnblogs.com/shouce/archive/2016/03/07/5249329.html
-Advertisement-
Play Games

出處: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" xmln


出處: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

  

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、在body中用onload: <body onload="conver()"> 2、在腳本中用window.onload: <script type="text/javascript"> window.onload=about;//不要括弧function about(){ var beatle
  • 虛擬鍵盤,移動web開發的痛。
  • 用CSS實現圖片垂直居中的方法有很多,針對移動端設備可以用CSS3伸縮盒來實現圖片垂直居中。 代碼如下: <div class="box"> <img src="1.png" alt=""> </div> 1 .box{ 4 display: flex; /*容器為伸縮盒*/ 5 align-ite
  • setTimeout(function() { window.location.href='你要跳轉到的頁面的地址';}, 時間以秒為單位); 例如: setTimeout(function() {window.location.href='http://www.bt720p.com';}, 100
  • 插入到functions.php目錄裡面 //保護後臺登錄add_action('login_enqueue_scripts','login_protection'); function login_protection(){ if($_GET['wangyu'] != '1414060215478
  • 只要使用過jQuery的,想必對ready都不陌生,$(function(){})和$(document).ready(function(){})的使用更是習以為常。那它內部是怎麼實現的呢,嘿嘿,我們不妨一同學習學習
  • fancybox可以彈出很多窗體,甚至一個swf格式的小視頻。但這樣的swf視頻播放的時候並沒有任何的控制項。只能重頭看到尾,或者關閉。我們可以利用fancybox彈出div盒子的方式配合html5很快的寫出彈出一個小視頻的代碼。首先,效果如下圖所示。點擊播放的圖片,彈出播放視頻。背景自動虛化。 首先
  • 今天分享使用html+css3+少量jquery實現滑鼠移入移出圖片生成隨機動畫,我們先看最終效果圖(截圖為靜態效果,做出來可是動態的喲) 左右旋轉 上下移動 縮放 由於時間關係我就不一步步解析各段代碼所代表含義,我這裡就給出一些思路及關鍵 代碼: 1、首先使用ul li展現4張圖片 本示例中不僅使...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...