HTTP Helper for SynchronousRequest

/ 0评 / 0

 

Only an easy http request class for freshman in objective-c.

HttpHelper.h

#import <Foundation/Foundation.h>
@interface HttpHelper : NSObject
+ (NSString *)getHtml: (NSString *)url;
+ (NSString *)getHtml: (NSString *)url Encoding:(NSStringEncoding)encoding;
+ (NSString *)getHtmlbyPost: (NSString *)url withPostData:(NSString *)postStr;
@end

HttpHelper.m

#import "HttpHelper.h"
@implementation HttpHelper
//获取页面源码,编码UTF8
+ (NSString *)getHtml: (NSString *)url
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:url]];
    [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [request setTimeoutInterval:5.0];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil
                                                           error:nil];

    return [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
//获取页面源码
+ (NSString *)getHtml: (NSString *)url Encoding:(NSStringEncoding)encoding
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:url]];
    [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [request setTimeoutInterval:5.0];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil
                                                           error:nil];

    return [[NSString alloc] initWithData:returnData encoding:encoding];
}
//post数据
+ (NSString *)getHtmlbyPost: (NSString *)url withPostData:(NSString *)postStr
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setURL:[NSURL URLWithString:url]];
    [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [request setTimeoutInterval:5.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [request setValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
    NSString* len = [NSString stringWithFormat:@"%ld", [postData length]];
    [request setValue:len forHTTPHeaderField:@"Content-Length"];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil
                                                           error:nil];

    return [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
@end

 

发表评论

邮箱地址不会被公开。 必填项已用*标注