IOS4.2網(wǎng)絡(luò)學(xué)習(xí)之發(fā)送HTTP請(qǐng)求
IOS4.2網(wǎng)絡(luò)學(xué)習(xí)之發(fā)送HTTP請(qǐng)求是而本文呢要介紹的內(nèi)容,主要介紹了發(fā)送HTTP請(qǐng)求的原理,讓我學(xué)習(xí)了IOS相關(guān)的網(wǎng)絡(luò)內(nèi)容,先來(lái)看詳細(xì)內(nèi)容。
開(kāi)發(fā)環(huán)境 客戶(hù)端: mac os x 10.6.6 ,ios 4.2 + xcode3.2.5 服務(wù)端:windows xp + iis + asp.net
代碼如下:
- - (IBAction) sendHttp : (id) sender{
- //此處進(jìn)行GET方式 發(fā)送http請(qǐng)求
- //如有中文要進(jìn)行NSUTF8StringEncoding編碼
- NSString *urlString =[[NSString stringWithFormat:@"http://127.0.0.1/default.aspx?uc=%@",@"test"
- stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- //初始化http請(qǐng)求,并自動(dòng)內(nèi)存釋放
- NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
- [request setURL:[NSURL URLWithString:urlString]];
- [request setHTTPMethod:@"GET"];
- NSString *contentType = [NSString stringWithFormat:@"text/xml"];
- [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
- NSHTTPURLResponse *urlResponse = nil;
- NSError *error = [[NSError alloc] init];
- //同步返回請(qǐng)求,并獲得返回?cái)?shù)據(jù)
- NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
- NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
- //請(qǐng)求返回狀態(tài),如有中文無(wú)法發(fā)送請(qǐng)求,并且stausCode 值為 0
- NSLog(@"response code:%d",[urlResponse statusCode]);
- if([urlResponse statusCode] >= 200 && [urlResponse statusCode] <300){
- NSLog(@"response:%@",result);
- messag.text = [NSString stringWithFormat:@"%@",result];
- }
- }
服務(wù)端:
default.aspx文件內(nèi)容如下(清除自動(dòng)生成的文件內(nèi)容,只保存如下內(nèi)容)
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
default.aspx.cs文件
在Page_Load方式中添加如下代碼
- if (Request.Params["uc"] != null )
- {
- string userAcount = Request.Params["uc"];
- Response.Write("success" + userAcount );
- }
- else
- {
- Response.Write("fail");
- }
好,在代碼已編寫(xiě)完,發(fā)布iis站點(diǎn),進(jìn)行測(cè)試.
小結(jié):IOS4.2網(wǎng)絡(luò)學(xué)習(xí)之發(fā)送HTTP請(qǐng)求的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!