CocoaPods trunk is moving to be read-only. Read more on the blog, there are 9 months to go.

FJHttpClient 0.0.2

FJHttpClient 0.0.2

TestsTested
LangLanguage Obj-CObjective C
License MIT
ReleasedLast Release Aug 2017

Maintained by jeff_njut.



 
Depends on:
AFNetworking>= 0
JSONModel>= 0
YYModel>= 0
CocoaSecurity>= 0
 

  • By
  • jeff_njut

How To Get Started

FJHttpClient helps to prompt high RESTful api integration and simplfy usage of http(s) request. FJHttpClient is based on JSONModel,YYModel & AFNetwork to achieve automatical serializing request and de-serializing response. FJHttpClient supports installing the library in a project.

Podfile

To integrate FJHttpClient into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'FJHttpClient', :git => 'https://github.com/jeffnjut/FJHttpClient.git'

Then, run the following command:

$ pod install

If any update occurs, run the following command:

$ pod update

Import

Import FJHttpClient header file

If only HTTP(s) functional API included, import thus

#import <FJHttpClient/FJHttpClient.h>

Except that import the following for more category

#import <FJHttpClient/FJHttpClientHeader.h>

Usage

'FJHttpClientConfig' Object Definition

hostUrl                   // [Optional] Host url

timeout_non_multipart     // [Optional] Max time for a common post

timeout_multipart         // [Optional] Max time for a multi-part post

enableRelativePath        // [Optional] Whether full url or relative url enabled, Default is YES. 
                          // YES: method 'relativePath' must be implemented in sub-class of BaseRequest. Both full url and relative url(hostUrl must be given) are acceptable.
                          // NO : method 'relativePath' could be omitted.

headerFields              // [Optional] Set HTTP/HTTPS request header-fields

requestSerializer         // [Optional] AFNetworking Request Serializer 

responseSerializer        // [Optional] AFNetworking Response Serializer

buildCommonParamsBlock    // [Optional] A block for building common request parameters

processRelativePathBlock  // [Optional] A block for modifing relative url

enableLog                 // [Optional] Whether enable logging
                          // YES: printing log 
                          // NO : do not printing

jsonModelType             // [Optional] The Model for de-serializing json, default is JSONModel

Create a 'FJHttpClientConfig' object

FJHttpClientConfig *config = [FJHttpClientConfig new];

config.hostUrl = @"ur url";
config.enableRelativePath = YES;
config.headerFields = nil;

config.buildCommonParamsBlock = ^(NSMutableDictionary **params){

    // get params for request
    NSMutableDictionary *mutableParam = *params;

    // the common paramters
    NSMutableDictionary *dict = @{@"xxx":@"token",
                                  @"320":@"screenwidth"}

    // combine params for request & the common paramters
    [mutableParam addEntriesFromDictionary:dict];
};

config.processRelativePathBlock = ^(NSMutableString **relativeUrl) {

    // get url for request
    NSMutableString *url = *relativeUrl;

    // modify the original url
    [url insertString:[NSString stringWithFormat:@"/%@",@"v5"] atIndex:0];
    NSString *cur = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [url replaceCharactersInRange:NSMakeRange(0, url.length) withString:cur];
};

Then, 'FJHttpClient' goes with the 'FJHttpClientConfig'

FJHttpClient *client = [FJHttpClient sharedInstance:config];

What's Basic Request/Response API for ?

All your API's request/response model must be inherited from BaseRequest/BaseResponse. You'll find that BaseRequest/BaseResponse model is also inherited from JSONModel, in order to automatically deserialize HTTP(s) response to your API's response model.

BaseRequest

@interface BaseRequest : JSONModel

- (NSString*)relativePath;

@end
@implementation BaseRequest

- (NSString*)relativePath {
return nil;
}

@end

BaseResponse

@interface BaseResponse : JSONModel

@end
@implementation BaseResponse

@end

Define a Customized Request/Response API

Request API:
@interface APICommonDictRequest : BaseRequest

@end

// If enableRelativePath is YES, relativePath method implemetation is a MUST.
@implementation APICommonDictRequest

- (NSString *)relativePath {
    return @"/?m=index&c=data_dict";
}

@end
Response JSON Format:
{
    "code": 0,
    "msg": "awesome, that's correct!!!",
    "data": {
                "name": "jeff",
                "age": 20
            }
}
Response Object:
@class Person;

@interface APICommonDictResponse : BaseResponse

// Fill model corresponding to json response
@property (nonatomic, assign) int code;
@property (nonatomic, copy) NSString *msg;
@property (nonatomic, strong) Person *data;

@end

@interface Person : JSONModel

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;

@end

Post Request

[[FJHttpClient sharedInstance] post:[APICommonDictRequest new] multipart:nil callback:^(id data, NSError *error) {
    NSLog(@"data : %@  error : %@", data, error);
}];

Multipart-Post

@interface MultipartData : NSObject

@property (nonatomic, copy) NSString *name;       // 参数名

@property (nonatomic, copy) NSString *fileName;   // 文件名

@property (nonatomic, copy) NSString *mineType;   // 比如图片"image/jpg"

@property (nonatomic, strong) NSData *data;       // 比如图片的Data

@end

GET Sample (Lookup an app info from itune connect)

Main
FJHttpClientConfig *config = [FJHttpClientConfig new];

config.enableRelativePath = YES;

config.responseSerializer = [AFJSONResponseSerializer serializer];

config.jsonModelType = JsonModelType_YYModel;

FJHttpClient *client = [FJHttpClient sharedInstance:config];

GetAppInfoRequest *getAppRequest = [GetAppInfoRequest new];

getAppRequest.bundleId = @"ur app bundle id";

[client get:getAppRequest callback:^(id data, NSError *error) {
    NSLog(@"data : %@  error : %@", data, error);
}];
Resquest/Response API
@interface GetAppInfoRequest : BaseRequest

@property (nonatomic, copy) NSString *bundleId;

@end
@implementation GetAppInfoRequest

- (NSString *)relativePath {
    return @"https://itunes.apple.com/lookup";
}

@end
@interface GetAppInfoResponse : BaseResponse

@property (nonatomic, assign) int resultCount;
@property (nonatomic, strong) NSMutableArray<AppInfoResult, Optional> *results;

@end
@implementation GetAppInfoResponse

@end
Model
@class AppInfoResult;
@protocol AppInfoResult;
@protocol NSString;

@interface AppInfoResult : JSONModel
@property (nonatomic, copy) NSString<Optional> *artworkUrl512;
@property (nonatomic, copy) NSString<Optional> *artistViewUrl;
@property (nonatomic, copy) NSString<Optional> *kind;
@property (nonatomic, strong) NSMutableArray<NSString,Optional> *screenshotUrls;
@property (nonatomic, copy) NSString<Optional> *trackCensoredName;
@property (nonatomic, copy) NSString<Optional> *sellerName;
@property (nonatomic, copy) NSString<Optional> *version;
@property (nonatomic, copy) NSString<Optional> *formattedPrice;
@property (nonatomic, copy) NSString<Optional> *description;

@end

@protocol AppInfoResult

@end

@protocol NSString

@end
@implementation AppInfoResult

@end

Contribute

Feel free to open an issue or pull request, if you need help or there is a bug.

Contact

Todo

  • Documentation

License

FJHttpClient is available under the MIT license. See the LICENSE file for more info.

The MIT License (MIT)

Copyright (c) 2017 Jeff

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.