Skip to content

Commit

Permalink
all is well
Browse files Browse the repository at this point in the history
  • Loading branch information
dtboy1995 committed May 22, 2017
1 parent 492791f commit 18d3d7d
Show file tree
Hide file tree
Showing 17 changed files with 459 additions and 120 deletions.
120 changes: 110 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ A sex http library, Simple and convenient, support many cache mechanism, simplif

# useful if you
- The GET request requires processing in different cases, and the request results are quickly converted to Object
- Your server is based on JSON and follows the REST specification

# install
```java
Expand All @@ -15,38 +16,119 @@ allprojects {
}
//Add it in your module build.gradle
dependencies {
compile 'com.github.dtboy1995:android-sex-http:0.0.1'
compile 'com.github.dtboy1995:android-sex-http:0.0.2'
}
// if compile has errors
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
```

# usage
```java
// execute once
// init cache core
HTTPUtil.initHttpCache(context);
// sample
// init the baseurl then Request().setUrl('/foo') -> baseurl + '/foo'
HTTPUtil.BASE_URL = "http://domain";
// set the get request cache key unique identification request
HTTPUtil.setCacheKey('user_id');
// set http or https port
HTTPUtil.setHttpPort(8080); // default 80
HTTPUtil.setHttpsPort(8888); // default 443
// init global response-posted include disconnected()-> handle all disconnected of requests fail()-> handle all fail of requests
HTTPUtil.globalResponseHandler = new IGlobalResponseHandler() {
@Override
public void disconnected(Context context) {
Toast.makeText(context, "no networking!", Toast.LENGTH_SHORT).show();
}

@Override
public void fail(String response, Context context) {
Toast.makeText(context, "error happened!", Toast.LENGTH_SHORT).show();
}
};
// init global pre-request for example addHeaders() -> set header for all request
HTTPUtil.globalRequestHandler = new IGlobalRequestHandler() {
@Override
public List<Header> addHeaders() {
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("version", "1.0.2"));
// add ...
return headers;
}
};
// get sample
HTTPModel
.build()
.setUrl("http://apistage.wenanle.com/banners")
.setCachePolicy(CachePolicy.NoCache)
.setUrl("/foo")
.setCachePolicy(CachePolicy.NoCache) // default CacheAndRemote
.setContext(this)
.setMethod(HTTPMethod.GET)
.setResult(new HTTPResult<List<Banner>>() {
.setMethod(HTTPMethod.GET) // default GET
.setResult(new HTTPResult<T>() {
@Override
public void ok(Header[] headers, List<Banner> response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
public void ok(Header[] headers, T response) {
// your code
}

@Override
public void no(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();

}

// if need can override
@Override
public void cache(String response) {
// this will call ok()
super.cache(response);
// you can comment out super.cache(response)
// to deal with the response
}
})
.done();
// post sample
Request
.build()
.setMethod(Method.POST)
.addHeader("token","foo_token")
.setUrl("/foo")
.setBody(Body.build().addKvs("username","foo").addKvs("age", 25).done())
.setResponse(new Response<T>(){

@Override
public void ok(Header[] headers, T response) {

}

@Override
public void no(String error) {

}
})
.done();
// put delete similar
// if you want to handle raw json string yourself
Request
.build()
.setResponseRaw(new ResponseRaw() {
@Override
public void ok(Header[] headers, String response) {

}

@Override
public void no(String error) {

}
})
.done();
// ...
```
# cache policy
- **NoCache**
Expand All @@ -61,7 +143,25 @@ HTTPModel
- If the network is unblocked, remote server data is obtained and cached data is obtained without a network connection

# response
- **HTTPResult&lt;T&gt;**
- **Response&lt;T&gt;**
- T is data type that needs to be serialized
- Can override cache() to handle the cache by yourself
- Can override disconneted() to deal with no network
- **ResponseRaw**
- Returns the JSON string directly

# request
- setMethod() default GET
- Method.GET
- Method.POST
- Method.PUT
- Method.DELETE
- setBody(Map<String, Object> body) set reqeust body
- you can use Body.bulid().addKvs(key,value).done()
- setHeaders(Map<String, String> headers)
- addHeader(String key, String value)
- setUrl(String url)
- setCachePolicy(CachePolicy policy) default CacheAndRemote
- setIsUseBaseUrl(bool isUseBaseUrl) default true
- setIsRawResponse(bool isRawResponse) default false
- if you want to user setResponseRaw() then you show setIsRawResponse(true)
1 change: 0 additions & 1 deletion library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,5 @@ dependencies {
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
testCompile 'junit:junit:4.12'
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,16 @@
import android.support.test.runner.AndroidJUnit4;

import com.prajna.dtboy.http.CachePolicy;
import com.prajna.dtboy.http.HTTPMethod;
import com.prajna.dtboy.http.HTTPModel;
import com.prajna.dtboy.http.HTTPResult;
import com.prajna.dtboy.http.Method;
import com.prajna.dtboy.http.Request;
import com.prajna.dtboy.http.Response;
import com.prajna.dtboy.http.HTTPUtil;

import org.junit.Test;
import org.junit.runner.RunWith;

import cz.msebera.android.httpclient.Header;

import static org.junit.Assert.*;

/**
* Instrumentation test, which will execute on an Android device.
*
Expand All @@ -31,13 +29,13 @@ public void useAppContext() throws Exception {
HTTPUtil.initHttpCache(appContext);
//
// assertEquals("com.prajna.dtboy.test", appContext.getPackageName());
HTTPModel
Request
.build()
.setUrl("www.baidu.com")
.setCachePolicy(CachePolicy.CacheAndRemote)
.setContext(appContext)
.setMethod(HTTPMethod.GET)
.setResult(new HTTPResult<String>() {
.setMethod(Method.GET)
.setResponse(new Response<String>() {
@Override
public void ok(Header[] headers, String response) {

Expand Down
27 changes: 27 additions & 0 deletions library/src/main/java/com/prajna/dtboy/http/Body.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.prajna.dtboy.http;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
*/

public class Body {

private Map<String, Object> kvs = new HashMap<>();

public static Body build() {
Body body = new Body();
return body;
}

public Body addKvs(String key, Object value) {
kvs.put(key, value);
return this;
}

public Map<String, Object> done() {
return this.kvs;
}
}
11 changes: 5 additions & 6 deletions library/src/main/java/com/prajna/dtboy/http/CachePolicy.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package com.prajna.dtboy.http;

/**
* 缓存策略枚举
*/
public enum CachePolicy {
NoCache, //不要缓存
CacheOnly, //只要缓存
CacheAndRemote, //双重回调 先使用缓存后使用服务器
IgnoreCache, //忽略缓存 会缓存起来但是 不会使用缓存
CacheOrRemote; //如果有网就请求 没网就缓存
NoCache,
CacheOnly,
CacheAndRemote,
IgnoreCache,
CacheOrRemote;
}
51 changes: 39 additions & 12 deletions library/src/main/java/com/prajna/dtboy/http/HTTPHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,75 @@
import cz.msebera.android.httpclient.Header;

/**
* HTTP请求处理器
*/
public class HTTPHandler extends TextHttpResponseHandler {

HTTPModel model;
Request model;

public HTTPHandler(HTTPModel model) {
public HTTPHandler(Request model) {
this.model = model;
}

@Override
public void onSuccess(int status, Header[] headers, String response) {
Log.e(getClass().getName(), response);
if (model.getMethod() == HTTPMethod.GET) {
if (model.getMethod() == Method.GET) {
switch (model.getCachePolicy()) {
case NoCache:
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
break;
case IgnoreCache:
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
HTTPUtil.cache.put(model.getCacheKey(), response);
break;
case CacheOnly:
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
HTTPUtil.cache.put(model.getCacheKey(), response);
break;
case CacheAndRemote:
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
HTTPUtil.cache.put(model.getCacheKey(), response);
break;
case CacheOrRemote:
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
}
} else {
model.getResult().success(status, headers, response);
if (model.getIsRawResponse()) {
model.getResponseRaw().success(status, headers, response);
} else {
model.getResult().success(status, headers, response);
}
}
}

@Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
Log.e(getClass().getName(), s+"");
model.getResult().fail(s, throwable);
if (model.getIsRawResponse()) {
model.getResponseRaw().fail(s, model.context);
} else {
model.getResult().fail(s, model.context);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@
import cz.msebera.android.httpclient.Header;

/**
* 自定义请求回调接口
* |success| 请求成功的回调
* |cache| 返回cache的回调 如不重写cache 该方法默认回调到ok()上
* |fail| 请求失败的回调
* |disconnected| 没有网络的回调
*/
public interface HTTPResultHandler {
void success(int status, Header[] headers, String response);

void cache(String response);

void fail(String errorMsg, Throwable throwable);
void fail(String errorMsg, Context context);

void disconnected(Context context);
}
Loading

0 comments on commit 18d3d7d

Please sign in to comment.