Skip to content

Commit

Permalink
fix header bug and add gzip support
Browse files Browse the repository at this point in the history
  • Loading branch information
panxw committed May 2, 2016
1 parent 7429cce commit 81e501e
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 106 deletions.
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 41 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ Tested in Android 5.1, 6.0.
<dependency>
<groupId>com.panxw.volley</groupId>
<artifactId>library</artifactId>
<version>1.0.1</version>
<version>1.0.2</version>
</dependency>

#####for Gradle
dependencies {
compile 'com.panxw.volley:library:1.0.1'
compile 'com.panxw.volley:library:1.0.2'
}

#####latest jars for download
[com.panxw.volley-1.0.1-classes.jar](https://github.com/panxw/android-volley-manager/blob/master/release/com.panxw.volley-1.0.1-classes.jar?raw=true)
[com.panxw.volley-1.0.2-classes.jar](https://github.com/panxw/android-volley-manager/blob/master/release/com.panxw.volley-1.0.2-classes.jar?raw=true)

##Sample
#####init RequestManager in your Application
Expand All @@ -42,67 +42,78 @@ Tested in Android 5.1, 6.0.

#####use RequestManager to load data
public class MainActivity extends Activity implements RequestListener {
private static final String OUT_FILE = "upload.txt";
private static final String OUT_DATA = "sadf464764sdf3ds1f3adsf78921355u2390q3rtheslafkhsdafhreasof";
private static final String POST_URL = "http://allthelucky.ap01.aws.af.cm/memoServer";

private static final String TAG = "VolleyTest";

private static final String GET_URL = "http://www.panxw.com/about.html";

private static final String POST_URL = "http://www.panxw.com/index.php";

private static final String POST_JSON = "{\"action\":\"test\", \"info\":\"hello world\"}";
private static final String GET_URL = "https://raw.githubusercontent.com/panxw/android-volley-manager/master/test.txt";

private static final String OUT_FILE = "upload.txt";

private static final String OUT_DATA = "df464764sdf3ds1f3adsf789213557r12-34912-482130487321";

private static final String UPLOAD_URL = "http://www.splashpadmobile.com/upload.php";

private LoadController mLoadController = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

this.testPost();

this.testGet();
this.testPost();
this.testFileUpload();
}

private void testPost() {//test post
mLoadController = RequestManager.getInstance().post(POST_URL, POST_JSON, this, 0);
}

private void testGet() {//test GET

private void testGet() {
mLoadController = RequestManager.getInstance().get(GET_URL, this, 1);
}

private void testFileUpload() {//test POST(with file) in RequestMap

private void testPost() {
mLoadController = RequestManager.getInstance().post(POST_URL, POST_JSON,
this, 0);
}

private void testFileUpload() {
MainActivity.prepareFile(this);

RequestMap params = new RequestMap();
File uploadFile = new File(this.getFilesDir(), OUT_FILE);
params.put("uploadedfile", uploadFile);
params.put("share", "1");

mLoadController = RequestManager.getInstance().post(UPLOAD_URL, params, this, 2);

mLoadController = RequestManager.getInstance().post(UPLOAD_URL, params,
this, 2);
}

@Override
public void onSuccess(String response, Map<String, String> headers,
String url, int actionId) {
System.out.println("actionId:" + actionId + ", OnSucess!\n" + response);
Log.d(TAG, "actionId:" + actionId + ", OnSucess!\n" + response);
}

@Override
public void onError(String errorMsg, String url, int actionId) {
System.out.println("actionId:" + actionId + ", onError!\n" + errorMsg);
Log.d(TAG, "actionId:" + actionId + ", onError!\n" + errorMsg);
}

@Override
public void onRequest() {
System.out.println("request send...");
Log.d(TAG, "request send...");
}

@Override
public void onBackPressed() {
super.onBackPressed();
if (mLoadController != null) {
mLoadController.cancel();
}
}

private static void prepareFile(Context context) {
FileOutputStream fos = null;
try {
Expand All @@ -124,6 +135,7 @@ Tested in Android 5.1, 6.0.
}
}
}

}

####Author
Expand Down
2 changes: 1 addition & 1 deletion android-volley-manager.iml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="true">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ developerName = pan
developerEmail = [email protected]

# bintray.gradle use
libraryVersion = 1.0.1
libraryVersion = 1.0.2

licenseLabel = ["Apache-2.0"]

Expand Down
4 changes: 2 additions & 2 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ apply plugin: 'com.jfrog.bintray'

version = libraryVersion
android {
compileSdkVersion 20
buildToolsVersion '20.0.0'
compileSdkVersion 22
buildToolsVersion '22.0.1'
resourcePrefix 'android_lib_'
defaultConfig {
minSdkVersion 9
Expand Down
21 changes: 3 additions & 18 deletions library/library.iml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":library" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="com.panxw.volley" external.system.module.version="1.0.0" type="JAVA_MODULE" version="4">
<module external.linked.project.id=":library" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="com.panxw.volley" external.system.module.version="1.0.1" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
Expand Down Expand Up @@ -27,7 +27,7 @@
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="false">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
<exclude-output />
Expand Down Expand Up @@ -65,34 +65,19 @@
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/docs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/poms" />
<excludeFolder url="file://$MODULE_DIR$/build/reports" />
<excludeFolder url="file://$MODULE_DIR$/build/test-results" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 20 Platform" jdkType="Android SDK" />
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
10 changes: 8 additions & 2 deletions library/src/main/java/com/android/volley/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
Expand Down Expand Up @@ -115,6 +116,11 @@ public interface Method {
/** An opaque token tagging this request; used for bulk cancellation. */
private Object mTag;

/**
* map for request headers
*/
private Map<String, String> mHeaders = new HashMap<String, String>();

/**
* Creates a new request with the given URL and error listener. Note that
* the normal response listener is not provided here as delivery of responses
Expand Down Expand Up @@ -360,8 +366,8 @@ public boolean isCanceled() {
* provide these values.
* @throws AuthFailureError In the event of auth failure
*/
public Map<String, String> getHeaders() throws AuthFailureError {
return Collections.emptyMap();
public Map<String, String> getHeaders() throws AuthFailureError{
return mHeaders;
}

/**
Expand Down
14 changes: 6 additions & 8 deletions library/src/main/java/com/android/volley/http/HttpResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import java.util.zip.GZIPInputStream;

public class HttpResponse {
public static final int SC_CONTINUE=100;
public static final int SC_OK = 200;
public static final int SC_NO_CONTENT=204;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_FORBIDDEN = 403;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_OK = 200;

private int responseCode;
private String responseMessage;
Expand Down Expand Up @@ -56,18 +58,14 @@ public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}

public void checkGzip() throws IOException{
public boolean isGzipEnable(){
if(httpHeaders != null) {
String acceptEncoding = httpHeaders.get("Content-Encoding");
if(acceptEncoding != null && acceptEncoding.contains("gzip")) {
if(entityFromConnection != null) {
InputStream is = entityFromConnection.getContent();
if(is != null) {
entityFromConnection.setContent(new GZIPInputStream(is));
}
}
return true;
}
}
return false;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,6 @@ protected Map<String, String> getParams() throws AuthFailureError {
return null;//process as json, xml or MultipartRequestParams
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (null == headers || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
return headers;
}

@Override
public String getBodyContentType() {
if (httpEntity != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,13 @@ public LoadController sendRequest(int method, final String url, Object data,
if(requestHeaders.get(ACCEPT_ENCODING) == null) {
requestHeaders.put(ACCEPT_ENCODING, GZIP);
}

try {
request.getHeaders().putAll(requestHeaders);
} catch (AuthFailureError e) {
e.printStackTrace();
}

//set request retry policy
RetryPolicy retryPolicy = new DefaultRetryPolicy(timeoutCount,
retryTimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(retryPolicy);
Expand Down
40 changes: 33 additions & 7 deletions library/src/main/java/com/android/volley/toolbox/HurlStack.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
Expand Down Expand Up @@ -108,13 +109,14 @@ public HttpResponse performRequest(Request<?> request, Map<String, String> addit
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
HttpResponse response = new HttpResponse(connection.getResponseCode(), connection.getResponseMessage());
response.setEntity(entityFromConnection(connection));
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
if (header.getKey() != null) {
response.addHeader(header.getKey(), header.getValue().get(0));
response.addHeader(header.getKey(), header.getValue().get(0));
}
}
response.checkGzip();
if (hasResponseBody(request.getMethod(), responseCode)) {
response.setEntity(entityFromConnection(connection, response.isGzipEnable()));
}
return response;
}

Expand All @@ -123,16 +125,26 @@ public HttpResponse performRequest(Request<?> request, Map<String, String> addit
* @param connection
* @return an HttpEntity populated with data from <code>connection</code>.
*/
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
HttpEntity entity = new HttpEntity();
InputStream inputStream;
private static HttpEntity entityFromConnection(HttpURLConnection connection, boolean isGzipEable){
HttpEntity entity = new HttpEntity();
InputStream inputStream = null;

try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
entity.setContent(inputStream);

//check gzip
if(isGzipEable) {
try{
entity.setContent(new GZIPInputStream(inputStream));
}catch (IOException e) {
entity.setContent(inputStream);
}
}else {
entity.setContent(inputStream);
}
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
Expand Down Expand Up @@ -236,4 +248,18 @@ private static void addBodyIfExists(HttpURLConnection connection, Request<?> req
out.close();
}
}

/**
* Checks if a response message contains a body.
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpResponse.SC_CONTINUE <= responseCode && responseCode < HttpResponse.SC_OK)
&& responseCode != HttpResponse.SC_NO_CONTENT
&& responseCode != HttpResponse.SC_NOT_MODIFIED;
}
}
Binary file added release/com.panxw.volley-1.0.2-classes.jar
Binary file not shown.
Loading

0 comments on commit 81e501e

Please sign in to comment.