After this method returns, subsequent calls to isDone() will always return 42 | * true. Subsequent calls to isCancelled() will always return true if this method returned 43 | * true. 44 | * 45 | * @param mayInterruptIfRunning true if the thread executing this request should be interrupted; 46 | * otherwise, in-progress requests are allowed to complete 47 | * @return false if the request could not be cancelled, typically because it has already 48 | * completed normally; true otherwise 49 | */ 50 | public boolean cancel(final boolean mayInterruptIfRunning) { 51 | final AsyncHttpRequest _request = request.get(); 52 | if (_request != null) { 53 | if (Looper.myLooper() == Looper.getMainLooper()) { 54 | new Thread(new Runnable() { 55 | @Override 56 | public void run() { 57 | _request.cancel(mayInterruptIfRunning); 58 | } 59 | }).start(); 60 | } else { 61 | _request.cancel(mayInterruptIfRunning); 62 | } 63 | } 64 | return false; 65 | } 66 | 67 | /** 68 | * Returns true if this task completed. Completion may be due to normal termination, an 69 | * exception, or cancellation -- in all of these cases, this method will return true. 70 | * 71 | * @return true if this task completed 72 | */ 73 | public boolean isFinished() { 74 | AsyncHttpRequest _request = request.get(); 75 | return _request == null || _request.isDone(); 76 | } 77 | 78 | /** 79 | * Returns true if this task was cancelled before it completed normally. 80 | * 81 | * @return true if this task was cancelled before it completed 82 | */ 83 | public boolean isCancelled() { 84 | AsyncHttpRequest _request = request.get(); 85 | return _request == null || _request.isCancelled(); 86 | } 87 | 88 | public boolean shouldBeGarbageCollected() { 89 | boolean should = isCancelled() || isFinished(); 90 | if (should) 91 | request.clear(); 92 | return should; 93 | } 94 | } -------------------------------------------------------------------------------- /src/com/it114/android/oneframework/core/OneApplication.java: -------------------------------------------------------------------------------- 1 | package com.it114.android.oneframework.core; 2 | 3 | import android.app.Application; 4 | import android.graphics.Bitmap; 5 | import android.os.Environment; 6 | import com.it114.android.oneframework.core.BuildConfig; 7 | import com.it114.android.oneframework.core.data.Config; 8 | import com.it114.android.oneframework.core.data.Constants; 9 | import com.it114.android.oneframework.core.util.FileUtil; 10 | import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache; 11 | import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; 12 | import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache; 13 | import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; 14 | import com.nostra13.universalimageloader.core.DisplayImageOptions; 15 | import com.nostra13.universalimageloader.core.ImageLoader; 16 | import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; 17 | import com.nostra13.universalimageloader.core.assist.ImageScaleType; 18 | import com.nostra13.universalimageloader.core.assist.QueueProcessingType; 19 | import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | 24 | /** 25 | * Created by andy on 10/9/2015. 26 | */ 27 | public class OneApplication extends Application { 28 | static OneApplication INSTANCE; 29 | @Override 30 | public void onCreate() { 31 | super.onCreate(); 32 | Config.debug = true; 33 | INSTANCE = this; 34 | initImageLoader(); 35 | } 36 | 37 | public static OneApplication getInstance(){ 38 | return INSTANCE; 39 | } 40 | 41 | @Override 42 | public void onTerminate() { 43 | super.onTerminate(); 44 | } 45 | 46 | @Override 47 | public void onLowMemory() { 48 | super.onLowMemory(); 49 | } 50 | 51 | @Override 52 | public void onTrimMemory(int level) { 53 | super.onTrimMemory(level); 54 | } 55 | 56 | 57 | private void initImageLoader() { 58 | DisplayImageOptions options = new DisplayImageOptions.Builder() 59 | .bitmapConfig(Bitmap.Config.RGB_565) 60 | .imageScaleType(ImageScaleType.EXACTLY) 61 | .cacheOnDisc(true) 62 | .displayer(new FadeInBitmapDisplayer(200)) 63 | .build(); 64 | File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR); 65 | ImageLoaderConfiguration.Builder configBuilder = null; 66 | try { 67 | configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext()) 68 | .memoryCache(new WeakMemoryCache()) 69 | .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500)) 70 | .denyCacheImageMultipleSizesInMemory() 71 | .threadPoolSize(3)//线程池内加载的数量 72 | .threadPriority(Thread.NORM_PRIORITY - 2) 73 | .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现 74 | .memoryCacheSize(2 * 1024 * 1024) 75 | .discCacheSize(50 * 1024 * 1024) 76 | .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密 77 | .tasksProcessingOrder(QueueProcessingType.LIFO) 78 | .discCacheFileCount(100) //缓存的文件数量 79 | //.discCache(new UnlimitedDiscCache(cacheDir)) 80 | .defaultDisplayImageOptions(options); 81 | } catch (IOException e) { 82 | e.printStackTrace(); 83 | } 84 | if (BuildConfig.DEBUG) { 85 | configBuilder.writeDebugLogs(); 86 | } 87 | ImageLoader.getInstance().init(configBuilder.build()); 88 | } 89 | 90 | public void setDebugModel(boolean debugModel){ 91 | if(debugModel) { 92 | Config.debug = true; 93 | } else { 94 | Config.debug = false; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Sample1/build.xml: -------------------------------------------------------------------------------- 1 | 2 |
Additionally, you can override the 31 | * {@link #onFailure(int, org.apache.http.Header[], String, Throwable)}, {@link #onStart()}, and 32 | * {@link #onFinish()} methods as required.
For example:
33 | *
34 | * AsyncHttpClient client = new AsyncHttpClient();
35 | * client.get("http://www.google.com", new TextHttpResponseHandler() {
36 | * @Override
37 | * public void onStart() {
38 | * // Initiated the request
39 | * }
40 | *
41 | * @Override
42 | * public void onSuccess(String responseBody) {
43 | * // Successfully got a response
44 | * }
45 | *
46 | * @Override
47 | * public void onFailure(String responseBody, Throwable e) {
48 | * // Response failed :(
49 | * }
50 | *
51 | * @Override
52 | * public void onFinish() {
53 | * // Completed the request (either success or failure)
54 | * }
55 | * });
56 | *
57 | */
58 | public abstract class TextHttpResponseHandler extends AsyncHttpResponseHandler {
59 |
60 | private static final String LOG_TAG = "TextHttpResponseHandler";
61 |
62 | /**
63 | * Creates new instance with default UTF-8 encoding
64 | */
65 | public TextHttpResponseHandler() {
66 | this(DEFAULT_CHARSET);
67 | }
68 |
69 | /**
70 | * Creates new instance with given string encoding
71 | *
72 | * @param encoding String encoding, see {@link #setCharset(String)}
73 | */
74 | public TextHttpResponseHandler(String encoding) {
75 | super();
76 | setCharset(encoding);
77 | }
78 |
79 | /**
80 | * Called when request fails
81 | *
82 | * @param statusCode http response status line
83 | * @param headers response headers if any
84 | * @param responseString string response of given charset
85 | * @param throwable throwable returned when processing request
86 | */
87 | public abstract void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable);
88 |
89 | /**
90 | * Called when request succeeds
91 | *
92 | * @param statusCode http response status line
93 | * @param headers response headers if any
94 | * @param responseString string response of given charset
95 | */
96 | public abstract void onSuccess(int statusCode, Header[] headers, String responseString);
97 |
98 | @Override
99 | public void onSuccess(int statusCode, Header[] headers, byte[] responseBytes) {
100 | onSuccess(statusCode, headers, getResponseString(responseBytes, getCharset()));
101 | }
102 |
103 | @Override
104 | public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
105 | onFailure(statusCode, headers, getResponseString(responseBytes, getCharset()), throwable);
106 | }
107 |
108 | /**
109 | * Attempts to encode response bytes as string of set encoding
110 | *
111 | * @param charset charset to create string with
112 | * @param stringBytes response bytes
113 | * @return String of set encoding or null
114 | */
115 | public static String getResponseString(byte[] stringBytes, String charset) {
116 | try {
117 | String toReturn = (stringBytes == null) ? null : new String(stringBytes, charset);
118 | if (toReturn != null && toReturn.startsWith(UTF8_BOM)) {
119 | return toReturn.substring(1);
120 | }
121 | return toReturn;
122 | } catch (UnsupportedEncodingException e) {
123 | Log.e(LOG_TAG, "Encoding response into string failed", e);
124 | return null;
125 | }
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/com/it114/android/oneframework/core/ui/activity/BaseFragmentActivity.java:
--------------------------------------------------------------------------------
1 | package com.it114.android.oneframework.core.ui.activity;
2 |
3 | import android.os.Bundle;
4 | import android.support.v4.app.FragmentActivity;
5 | import android.support.v4.app.FragmentManager;
6 | import android.support.v4.app.FragmentTransaction;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import butterknife.ButterKnife;
10 | import com.it114.android.oneframework.core.ui.fragment.SupportFragment;
11 | import com.it114.android.oneframework.core.ui.widget.titlebar.TitleBarListener;
12 | import com.it114.android.oneframework.core.ui.widget.titlebar.TitleBarViewImpl;
13 | import com.it114.android.oneframework.core.util.LogUtil;
14 | import com.it114.android.oneframework.core.util.ViewFinder;
15 |
16 | /**
17 | * Created by andy on 10/15/2015.
18 | */
19 | public abstract class BaseFragmentActivity extends FragmentActivity {
20 | protected final static String TAG = BaseFragmentActivity.class.getName();
21 | public ActivityCommon activityState = new ActivityCommonImpl();
22 | protected FragmentManager mFragmentManager = null;
23 | protected SupportFragment currentSupportFragment;
24 | protected ViewFinder mViewFinder;
25 | protected View titleBar;
26 | protected TitleBarViewImpl titleBarView;
27 |
28 | @Override
29 | protected void onCreate(Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 | setContentView(getLayoutId());
32 | ButterKnife.bind(this);
33 | mFragmentManager = getSupportFragmentManager();
34 | activityState.create(savedInstanceState);
35 | init(savedInstanceState);
36 | }
37 |
38 | public void initTitleBar(int titleBarLayoutId,TitleBarListener listener){
39 | if(titleBarLayoutId>0){
40 | if(this.titleBar == null)
41 | this.titleBar = findViewByIdWithFinder(titleBarLayoutId);
42 | this.titleBarView = new TitleBarViewImpl(this,titleBar);
43 | if(listener!=null){
44 | this.titleBarView.setTitleBarListener(listener);
45 | }
46 | } else {
47 | LogUtil.w(TAG, "invalid titleBarLayoutId");
48 | }
49 | }
50 |
51 | @Override
52 | public void setContentView(int layoutResID) {
53 | super.setContentView(layoutResID);
54 | mViewFinder = new ViewFinder(getWindow().getDecorView());
55 | }
56 |
57 | @Override
58 | public void setContentView(View view) {
59 | super.setContentView(view);
60 | mViewFinder = new ViewFinder(view);
61 | }
62 |
63 | @Override
64 | public void setContentView(View view, ViewGroup.LayoutParams params) {
65 | super.setContentView(view, params);
66 | mViewFinder = new ViewFinder(view);
67 | }
68 |
69 | public For example:
36 | *
37 | * AsyncHttpClient client = new AsyncHttpClient();
38 | * String[] allowedTypes = new String[] { "image/png" };
39 | * client.get("http://www.example.com/image.png", new BinaryHttpResponseHandler(allowedTypes) {
40 | * @Override
41 | * public void onSuccess(byte[] imageData) {
42 | * // Successfully got a response
43 | * }
44 | *
45 | * @Override
46 | * public void onFailure(Throwable e, byte[] imageData) {
47 | * // Response failed :(
48 | * }
49 | * });
50 | *
51 | */
52 | public abstract class BinaryHttpResponseHandler extends AsyncHttpResponseHandler {
53 |
54 | private static final String LOG_TAG = "BinaryHttpResponseHandler";
55 |
56 | private String[] mAllowedContentTypes = new String[]{
57 | RequestParams.APPLICATION_OCTET_STREAM,
58 | "image/jpeg",
59 | "image/png",
60 | "image/gif"
61 | };
62 |
63 | /**
64 | * Method can be overriden to return allowed content types, can be sometimes better than passing
65 | * data in constructor
66 | *
67 | * @return array of content-types or Pattern string templates (eg. '.*' to match every response)
68 | */
69 | public String[] getAllowedContentTypes() {
70 | return mAllowedContentTypes;
71 | }
72 |
73 | /**
74 | * Creates a new BinaryHttpResponseHandler
75 | */
76 | public BinaryHttpResponseHandler() {
77 | super();
78 | }
79 |
80 | /**
81 | * Creates a new BinaryHttpResponseHandler, and overrides the default allowed content types with
82 | * passed String array (hopefully) of content types.
83 | *
84 | * @param allowedContentTypes content types array, eg. 'image/jpeg' or pattern '.*'
85 | */
86 | public BinaryHttpResponseHandler(String[] allowedContentTypes) {
87 | super();
88 | if (allowedContentTypes != null) {
89 | mAllowedContentTypes = allowedContentTypes;
90 | } else {
91 | Log.e(LOG_TAG, "Constructor passed allowedContentTypes was null !");
92 | }
93 | }
94 |
95 | @Override
96 | public abstract void onSuccess(int statusCode, Header[] headers, byte[] binaryData);
97 |
98 | @Override
99 | public abstract void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error);
100 |
101 | @Override
102 | public final void sendResponseMessage(HttpResponse response) throws IOException {
103 | StatusLine status = response.getStatusLine();
104 | Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE);
105 | if (contentTypeHeaders.length != 1) {
106 | //malformed/ambiguous HTTP Header, ABORT!
107 | sendFailureMessage(
108 | status.getStatusCode(),
109 | response.getAllHeaders(),
110 | null,
111 | new HttpResponseException(
112 | status.getStatusCode(),
113 | "None, or more than one, Content-Type Header found!"
114 | )
115 | );
116 | return;
117 | }
118 | Header contentTypeHeader = contentTypeHeaders[0];
119 | boolean foundAllowedContentType = false;
120 | for (String anAllowedContentType : getAllowedContentTypes()) {
121 | try {
122 | if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
123 | foundAllowedContentType = true;
124 | }
125 | } catch (PatternSyntaxException e) {
126 | Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
127 | }
128 | }
129 | if (!foundAllowedContentType) {
130 | //Content-Type not in allowed list, ABORT!
131 | sendFailureMessage(
132 | status.getStatusCode(),
133 | response.getAllHeaders(),
134 | null,
135 | new HttpResponseException(
136 | status.getStatusCode(),
137 | "Content-Type not allowed!"
138 | )
139 | );
140 | return;
141 | }
142 | super.sendResponseMessage(response);
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/src/com/loopj/android/http/SaxAsyncHttpResponseHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | Android Asynchronous Http Client
3 | Copyright (c) 2011 James Smith
43 | * AsyncHttpClient ahc = new AsyncHttpClient();
44 | * FontHandler handlerInstance = ... ; // init handler instance
45 | * ahc.post("https://server.tld/api/call", new SaxAsyncHttpResponseHandler(handlerInstance){
46 | * @Override
47 | * public void onSuccess(int statusCode, Header[] headers, FontHandler t) {
48 | * // Request got HTTP success statusCode
49 | * }
50 | * @Override
51 | * public void onFailure(int statusCode, Header[] headers, FontHandler t){
52 | * // Request got HTTP fail statusCode
53 | * }
54 | * });
55 | *
56 | *
57 | * @param Handler extending {@link org.xml.sax.helpers.DefaultHandler}
58 | * @see org.xml.sax.helpers.DefaultHandler
59 | * @see AsyncHttpResponseHandler
60 | */
61 | public abstract class SaxAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
62 |
63 | /**
64 | * Generic Type of handler
65 | */
66 | private T handler = null;
67 | private final static String LOG_TAG = "SaxAsyncHttpResponseHandler";
68 |
69 | /**
70 | * Constructs new SaxAsyncHttpResponseHandler with given handler instance
71 | *
72 | * @param t instance of Handler extending DefaultHandler
73 | * @see org.xml.sax.helpers.DefaultHandler
74 | */
75 | public SaxAsyncHttpResponseHandler(T t) {
76 | super();
77 | if (t == null) {
78 | throw new Error("null instance of passed to constructor");
79 | }
80 | this.handler = t;
81 | }
82 |
83 | /**
84 | * Deconstructs response into given content handler
85 | *
86 | * @param entity returned HttpEntity
87 | * @return deconstructed response
88 | * @throws java.io.IOException
89 | * @see org.apache.http.HttpEntity
90 | */
91 | @Override
92 | protected byte[] getResponseData(HttpEntity entity) throws IOException {
93 | if (entity != null) {
94 | InputStream instream = entity.getContent();
95 | InputStreamReader inputStreamReader = null;
96 | if (instream != null) {
97 | try {
98 | SAXParserFactory sfactory = SAXParserFactory.newInstance();
99 | SAXParser sparser = sfactory.newSAXParser();
100 | XMLReader rssReader = sparser.getXMLReader();
101 | rssReader.setContentHandler(handler);
102 | inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
103 | rssReader.parse(new InputSource(inputStreamReader));
104 | } catch (SAXException e) {
105 | Log.e(LOG_TAG, "getResponseData exception", e);
106 | } catch (ParserConfigurationException e) {
107 | Log.e(LOG_TAG, "getResponseData exception", e);
108 | } finally {
109 | AsyncHttpClient.silentCloseInputStream(instream);
110 | if (inputStreamReader != null) {
111 | try {
112 | inputStreamReader.close();
113 | } catch (IOException e) { /*ignore*/ }
114 | }
115 | }
116 | }
117 | }
118 | return null;
119 | }
120 |
121 | /**
122 | * Default onSuccess method for this AsyncHttpResponseHandler to override
123 | *
124 | * @param statusCode returned HTTP status code
125 | * @param headers returned HTTP headers
126 | * @param t instance of Handler extending DefaultHandler
127 | */
128 | public abstract void onSuccess(int statusCode, Header[] headers, T t);
129 |
130 | @Override
131 | public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
132 | onSuccess(statusCode, headers, handler);
133 | }
134 |
135 | /**
136 | * Default onFailure method for this AsyncHttpResponseHandler to override
137 | *
138 | * @param statusCode returned HTTP status code
139 | * @param headers returned HTTP headers
140 | * @param t instance of Handler extending DefaultHandler
141 | */
142 | public abstract void onFailure(int statusCode, Header[] headers, T t);
143 |
144 | @Override
145 | public void onFailure(int statusCode, Header[] headers,
146 | byte[] responseBody, Throwable error) {
147 | onSuccess(statusCode, headers, handler);
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/com/it114/android/oneframework/core/util/SharedPreferenceUtil.java:
--------------------------------------------------------------------------------
1 | package com.it114.android.oneframework.core.util;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by andy on 10/18/2015.
7 | */
8 | public class SharedPreferenceUtil {
9 |
10 | private static final String sharedPreferenceFileName = "_default_shared_file_name";
11 | private static SharedPreferenceUtil instance = null;
12 |
13 | public static SharedPreferenceUtil getInstance(){
14 | if(instance == null){
15 | instance = new SharedPreferenceUtil();
16 | }
17 | return instance;
18 | }
19 |
20 | /**
21 | *
22 | * @param cookieName cookie file name ,or null ,use defaulte name .
23 | * @param key cookie key .
24 | * @param value
25 | */
26 | public boolean putString(Context context,String cookieName,String key,String value){
27 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).edit().putString(key, value).commit();
28 | }
29 | /**
30 | *
31 | * @param cookieName cookie file name ,or null ,use defaulte name .
32 | * @param key
33 | * @param value
34 | * @return
35 | */
36 | public boolean putBoolean(Context context,String cookieName,String key,boolean value){
37 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).edit().putBoolean(key, value).commit();
38 | }
39 | /**
40 | *
41 | * @param cookieName cookie file name ,or null ,use defaulte name .
42 | * @param key
43 | * @param value
44 | * @return
45 | */
46 | public boolean putFloat(Context context,String cookieName,String key,float value){
47 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).edit().putFloat(key, value).commit();
48 | }
49 | /**
50 | *
51 | * @param cookieName cookie file name ,or null ,use defaulte name .
52 | * @param key
53 | * @param value
54 | * @return
55 | */
56 | public boolean putLong(Context context,String cookieName,String key,long value){
57 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).edit().putLong(key, value).commit();
58 | }
59 |
60 | /**
61 | *
62 | * @param cookieName cookie file name ,or null ,use defaulte name .
63 | * @param key
64 | * @param value
65 | * @return
66 | */
67 | public boolean putInt(Context context,String cookieName,String key,int value){
68 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).edit().putInt(key, value).commit();
69 | }
70 |
71 | /**
72 | *
73 | * @param cookieName cookie file name ,or null ,use defaulte name .
74 | * @param key
75 | * @param defValue
76 | * @return
77 | */
78 | public String getString(Context context,String cookieName,String key,String defValue){
79 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).getString(key, defValue);
80 | }
81 |
82 | /**
83 | *
84 | * @param cookieName cookie file name ,or null ,use defaulte name .
85 | * @param key
86 | * @param defValue
87 | * @return
88 | */
89 | public boolean getBoolean(Context context,String cookieName,String key,boolean defValue){
90 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).getBoolean(key, defValue);
91 | }
92 | /**
93 | *
94 | * @param cookieName cookie file name ,or null ,use defaulte name .
95 | * @param key
96 | * @param defValue
97 | * @return
98 | */
99 | public float getFloat(Context context,String cookieName,String key,float defValue){
100 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).getFloat(key, defValue);
101 | }
102 | /**
103 | *
104 | * @param cookieName cookie file name ,or null ,use defaulte name .
105 | * @param key
106 | * @param defValue
107 | * @return
108 | */
109 | public int getInt(Context context,String cookieName,String key,int defValue){
110 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).getInt(key, defValue);
111 | }
112 | /**
113 | *
114 | * @param cookieName cookie file name ,or null ,use defaulte name .
115 | * @param key
116 | * @param defValue
117 | * @return
118 | */
119 | public long getLong(Context context,String cookieName,String key,long defValue){
120 | return context.getSharedPreferences(((cookieName==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).getLong(key, defValue);
121 | }
122 |
123 | /**
124 | * @param cookieName cookie file name ,or null ,use defaulte name .
125 | * @param key
126 | * @return
127 | */
128 | public boolean isExists(Context context,String cookieName,String key){
129 | return context.getSharedPreferences(((sharedPreferenceFileName ==null)? sharedPreferenceFileName :cookieName),Context.MODE_PRIVATE).contains(key);
130 | }
131 |
132 | /**
133 | * 清除cookie文件nei
134 | */
135 | public void clear(Context context,String fileName){
136 | context.getSharedPreferences(((sharedPreferenceFileName ==null)? sharedPreferenceFileName :fileName),Context.MODE_PRIVATE).edit().clear().commit();
137 | }
138 |
139 | /**从指定的cookie文件名中删除 key 的值
140 | * @param xmlname
141 | * @param key
142 | */
143 | public void remove(Context context,String xmlname,String key){
144 | context.getSharedPreferences(xmlname,Context.MODE_PRIVATE).edit().remove(key).commit();
145 | }
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/src/com/it114/android/oneframework/core/http/asynchttp/AsyncHttp.java:
--------------------------------------------------------------------------------
1 | package com.it114.android.oneframework.core.http.asynchttp;
2 |
3 | import com.it114.android.oneframework.core.OneApplication;
4 | import com.it114.android.oneframework.core.data.cache.HttpCacheManager;
5 | import com.it114.android.oneframework.core.bean.HttpCache;
6 | import com.it114.android.oneframework.core.http.Http;
7 | import com.it114.android.oneframework.core.http.HttpRequestHandler;
8 | import com.it114.android.oneframework.core.http.SafeHandler;
9 | import com.it114.android.oneframework.core.util.LogUtil;
10 | import com.loopj.android.http.AsyncHttpClient;
11 | import com.loopj.android.http.AsyncHttpResponseHandler;
12 | import com.loopj.android.http.RequestParams;
13 | import com.loopj.android.http.TextHttpResponseHandler;
14 | import org.apache.http.Header;
15 |
16 | /**
17 | * Created by andy on 10/12/2015.
18 | * 使用asyncHttpClient实现
19 | */
20 | public class AsyncHttp implements Http {
21 | private static AsyncHttpClient client = new AsyncHttpClient();
22 | private static AsyncHttpClient getHttpClient(){
23 | client.setTimeout(15000);
24 | return client;
25 | }
26 |
27 | private static void get(String url,RequestParams params, AsyncHttpResponseHandler responseHandler) {
28 | LogUtil.d(null, url+"?"+((params == null)?"":params.toString()));
29 | getHttpClient().get(OneApplication.getInstance().getInstance(), url, params, responseHandler);
30 | }
31 |
32 | private static void post(String url,RequestParams params,AsyncHttpResponseHandler responseHandler) {
33 | LogUtil.d(null, url+"?"+((params == null)?"":params.toString()));
34 | getHttpClient().post(OneApplication.getInstance(), url, params, responseHandler);
35 | }
36 |
37 | @Override
38 | public void get(final String url, RequestParams params,final HttpRequestHandler handler) {
39 | get(false,-1,url, params,handler);
40 | }
41 |
42 | @Override
43 | public void post(final String url, RequestParams params, final HttpRequestHandler handler) {
44 | post(false,-1,url, params,handler);
45 | }
46 |
47 | @Override
48 | public void put(String url, RequestParams map, String postContent, HttpRequestHandler handler) {
49 | //TODO
50 | }
51 |
52 | @Override
53 | public void delete(String url, RequestParams map, String postContent, HttpRequestHandler handler) {
54 | //TODO
55 | }
56 |
57 | @Override
58 | public void get(final boolean useCache,long cacheTime, final String url, final RequestParams params, final HttpRequestHandler handler){
59 | HttpCache cache = null;
60 | if(useCache) {
61 | cache = HttpCacheManager.get(url, params);
62 | if(cache!=null){
63 | if(cache.updateTime+cacheTime*1000 < System.currentTimeMillis()){ //走缓存逻辑
64 | SafeHandler.onSuccess(handler, cache.content);
65 | LogUtil.d(null, url + " use cache ,return local cache ");
66 | handler.onFinish();
67 | return;
68 | } else {}
69 | } else {}
70 | } else {}
71 | final String defValue = (cache==null)?"":cache.content;
72 | get(url,params, new TextHttpResponseHandler() {
73 | @Override
74 | public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
75 | SafeHandler.onFinish(handler);
76 | if("".equals(defValue)) {
77 | SafeHandler.onFailure(handler, responseString);
78 | } else {
79 | LogUtil.d(null,url+" return onFailure defValue is not null ,read cache");
80 | SafeHandler.onSuccess(handler, defValue);
81 | }
82 | }
83 |
84 | @Override
85 | public void onSuccess(int statusCode, Header[] headers, String responseString) {
86 | SafeHandler.onFinish(handler);
87 | SafeHandler.onSuccess(handler, responseString);
88 | if(useCache){
89 | HttpCacheManager.create(url,params,responseString);
90 | }
91 | }
92 | });
93 | }
94 |
95 | @Override
96 | public void post(final boolean useCache,long cacheTime, final String url, final RequestParams params, final HttpRequestHandler handler) {
97 | HttpCache cache = null;
98 | if(useCache) {
99 | cache = HttpCacheManager.get(url, params);
100 | if(cache!=null){
101 | if(cache.updateTime+cacheTime*1000 < System.currentTimeMillis()){ //走缓存逻辑
102 | SafeHandler.onSuccess(handler,cache.content);
103 | LogUtil.d(null, url + " use cache ,return local cache ");
104 | handler.onFinish();
105 | return;
106 | } else {}
107 | } else {}
108 | } else {}
109 | final String defValue = (cache==null)?"":cache.content;
110 | post(url, params, new TextHttpResponseHandler() {
111 | @Override
112 | public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
113 | SafeHandler.onFinish(handler);
114 | if ("".equals(defValue)) {
115 | SafeHandler.onFailure(handler, responseString);
116 | } else {
117 | LogUtil.d(null, url + " return onFailure defValue is not null ,read cache");
118 | SafeHandler.onSuccess(handler, defValue);
119 | }
120 | }
121 | @Override
122 | public void onSuccess(int statusCode, Header[] headers, String responseString) {
123 | SafeHandler.onFinish(handler);
124 | SafeHandler.onSuccess(handler, responseString);
125 | if (useCache) {
126 | HttpCacheManager.create(url, params, responseString);
127 | }
128 | }
129 | });
130 | }
131 |
132 | }
133 |
--------------------------------------------------------------------------------
/src/com/loopj/android/http/DataAsyncHttpResponseHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | Android Asynchronous Http Client
3 | Copyright (c) 2011 James Smith
4 | http://loopj.com
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | package com.loopj.android.http;
20 |
21 | import android.os.Message;
22 | import android.util.Log;
23 |
24 | import org.apache.http.HttpEntity;
25 | import org.apache.http.util.ByteArrayBuffer;
26 |
27 | import java.io.IOException;
28 | import java.io.InputStream;
29 |
30 | public abstract class DataAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
31 | private static final String LOG_TAG = "DataAsyncHttpResponseHandler";
32 |
33 | protected static final int PROGRESS_DATA_MESSAGE = 7;
34 |
35 | /**
36 | * Creates a new AsyncHttpResponseHandler
37 | */
38 | public DataAsyncHttpResponseHandler() {
39 | super();
40 | }
41 |
42 | /**
43 | * Fired when the request progress, override to handle in your own code
44 | *
45 | * @param responseBody response body received so far
46 | */
47 | public void onProgressData(byte[] responseBody) {
48 | Log.d(LOG_TAG, "onProgressData(byte[]) was not overriden, but callback was received");
49 | }
50 |
51 |
52 | final public void sendProgressDataMessage(byte[] responseBytes) {
53 | sendMessage(obtainMessage(PROGRESS_DATA_MESSAGE, new Object[]{responseBytes}));
54 | }
55 |
56 | // Methods which emulate android's Handler and Message methods
57 | @Override
58 | protected void handleMessage(Message message) {
59 | super.handleMessage(message);
60 | Object[] response;
61 |
62 | switch (message.what) {
63 | case PROGRESS_DATA_MESSAGE:
64 | response = (Object[]) message.obj;
65 | if (response != null && response.length >= 1) {
66 | try {
67 | onProgressData((byte[]) response[0]);
68 | } catch (Throwable t) {
69 | Log.e(LOG_TAG, "custom onProgressData contains an error", t);
70 | }
71 | } else {
72 | Log.e(LOG_TAG, "PROGRESS_DATA_MESSAGE didn't got enough params");
73 | }
74 | break;
75 | }
76 | }
77 |
78 | /**
79 | * Returns byte array of response HttpEntity contents
80 | *
81 | * @param entity can be null
82 | * @return response entity body or null
83 | * @throws java.io.IOException if reading entity or creating byte array failed
84 | */
85 | @Override
86 | byte[] getResponseData(HttpEntity entity) throws IOException {
87 |
88 | byte[] responseBody = null;
89 | if (entity != null) {
90 | InputStream instream = entity.getContent();
91 | if (instream != null) {
92 | long contentLength = entity.getContentLength();
93 | if (contentLength > Integer.MAX_VALUE) {
94 | throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
95 | }
96 | if (contentLength < 0) {
97 | contentLength = BUFFER_SIZE;
98 | }
99 | try {
100 | ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
101 | try {
102 | byte[] tmp = new byte[BUFFER_SIZE];
103 | int l, count = 0;
104 | // do not send messages if request has been cancelled
105 | while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
106 | buffer.append(tmp, 0, l);
107 | sendProgressDataMessage(copyOfRange(tmp, 0, l));
108 | sendProgressMessage(count, (int) contentLength);
109 | }
110 | } finally {
111 | AsyncHttpClient.silentCloseInputStream(instream);
112 | }
113 | responseBody = buffer.toByteArray();
114 | } catch (OutOfMemoryError e) {
115 | System.gc();
116 | throw new IOException("File too large to fit into available memory");
117 | }
118 | }
119 | }
120 | return responseBody;
121 | }
122 |
123 | /**
124 | * Copies elements from {@code original} into a new array, from indexes start (inclusive) to end
125 | * (exclusive). The original order of elements is preserved. If {@code end} is greater than
126 | * {@code original.length}, the result is padded with the value {@code (byte) 0}.
127 | *
128 | * @param original the original array
129 | * @param start the start index, inclusive
130 | * @param end the end index, exclusive
131 | * @return the new array
132 | * @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
133 | * @throws IllegalArgumentException if {@code start > end}
134 | * @throws NullPointerException if {@code original == null}
135 | * @see java.util.Arrays
136 | * @since 1.6
137 | */
138 | public static byte[] copyOfRange(byte[] original, int start, int end) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, NullPointerException {
139 | if (start > end) {
140 | throw new IllegalArgumentException();
141 | }
142 | int originalLength = original.length;
143 | if (start < 0 || start > originalLength) {
144 | throw new ArrayIndexOutOfBoundsException();
145 | }
146 | int resultLength = end - start;
147 | int copyLength = Math.min(resultLength, originalLength - start);
148 | byte[] result = new byte[resultLength];
149 | System.arraycopy(original, start, result, 0, copyLength);
150 | return result;
151 | }
152 | }
153 |
154 |
--------------------------------------------------------------------------------
/src/com/loopj/android/http/FileAsyncHttpResponseHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | Android Asynchronous Http Client
3 | Copyright (c) 2011 James Smith
4 | http://loopj.com
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | package com.loopj.android.http;
20 |
21 | import android.content.Context;
22 | import android.util.Log;
23 |
24 | import org.apache.http.Header;
25 | import org.apache.http.HttpEntity;
26 |
27 | import java.io.File;
28 | import java.io.FileOutputStream;
29 | import java.io.IOException;
30 | import java.io.InputStream;
31 |
32 | public abstract class FileAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
33 |
34 | protected final File mFile;
35 | protected final boolean append;
36 | private static final String LOG_TAG = "FileAsyncHttpResponseHandler";
37 |
38 | /**
39 | * Obtains new FileAsyncHttpResponseHandler and stores response in passed file
40 | *
41 | * @param file File to store response within, must not be null
42 | */
43 | public FileAsyncHttpResponseHandler(File file) {
44 | this(file, false);
45 | }
46 |
47 | /**
48 | * Obtains new FileAsyncHttpResponseHandler and stores response in passed file
49 | *
50 | * @param file File to store response within, must not be null
51 | * @param append whether data should be appended to existing file
52 | */
53 | public FileAsyncHttpResponseHandler(File file, boolean append) {
54 | super();
55 | AssertUtils.asserts(file != null, "File passed into FileAsyncHttpResponseHandler constructor must not be null");
56 | AssertUtils.asserts(file.getParentFile().mkdirs(), "Cannot create parent directories for requested File location");
57 | this.mFile = file;
58 | this.append = append;
59 | }
60 |
61 | /**
62 | * Obtains new FileAsyncHttpResponseHandler against context with target being temporary file
63 | *
64 | * @param context Context, must not be null
65 | */
66 | public FileAsyncHttpResponseHandler(Context context) {
67 | super();
68 | this.mFile = getTemporaryFile(context);
69 | this.append = false;
70 | }
71 |
72 | /**
73 | * Attempts to delete file with stored response
74 | *
75 | * @return false if the file does not exist or is null, true if it was successfully deleted
76 | */
77 | public boolean deleteTargetFile() {
78 | return getTargetFile() != null && getTargetFile().delete();
79 | }
80 |
81 | /**
82 | * Used when there is no file to be used when calling constructor
83 | *
84 | * @param context Context, must not be null
85 | * @return temporary file or null if creating file failed
86 | */
87 | protected File getTemporaryFile(Context context) {
88 | AssertUtils.asserts(context != null, "Tried creating temporary file without having Context");
89 | try {
90 | // not effective in release mode
91 | assert context != null;
92 | return File.createTempFile("temp_", "_handled", context.getCacheDir());
93 | } catch (IOException e) {
94 | Log.e(LOG_TAG, "Cannot create temporary file", e);
95 | }
96 | return null;
97 | }
98 |
99 | /**
100 | * Retrieves File object in which the response is stored
101 | *
102 | * @return File file in which the response is stored
103 | */
104 | protected File getTargetFile() {
105 | assert (mFile != null);
106 | return mFile;
107 | }
108 |
109 | @Override
110 | public final void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
111 | onFailure(statusCode, headers, throwable, getTargetFile());
112 | }
113 |
114 | /**
115 | * Method to be overriden, receives as much of file as possible Called when the file is
116 | * considered failure or if there is error when retrieving file
117 | *
118 | * @param statusCode http file status line
119 | * @param headers file http headers if any
120 | * @param throwable returned throwable
121 | * @param file file in which the file is stored
122 | */
123 | public abstract void onFailure(int statusCode, Header[] headers, Throwable throwable, File file);
124 |
125 | @Override
126 | public final void onSuccess(int statusCode, Header[] headers, byte[] responseBytes) {
127 | onSuccess(statusCode, headers, getTargetFile());
128 | }
129 |
130 | /**
131 | * Method to be overriden, receives as much of response as possible
132 | *
133 | * @param statusCode http response status line
134 | * @param headers response http headers if any
135 | * @param file file in which the response is stored
136 | */
137 | public abstract void onSuccess(int statusCode, Header[] headers, File file);
138 |
139 | @Override
140 | protected byte[] getResponseData(HttpEntity entity) throws IOException {
141 | if (entity != null) {
142 | InputStream instream = entity.getContent();
143 | long contentLength = entity.getContentLength();
144 | FileOutputStream buffer = new FileOutputStream(getTargetFile(), this.append);
145 | if (instream != null) {
146 | try {
147 | byte[] tmp = new byte[BUFFER_SIZE];
148 | int l, count = 0;
149 | // do not send messages if request has been cancelled
150 | while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
151 | count += l;
152 | buffer.write(tmp, 0, l);
153 | sendProgressMessage(count, (int) contentLength);
154 | }
155 | } finally {
156 | AsyncHttpClient.silentCloseInputStream(instream);
157 | buffer.flush();
158 | AsyncHttpClient.silentCloseOutputStream(buffer);
159 | }
160 | }
161 | }
162 | return null;
163 | }
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/src/com/loopj/android/http/MyRedirectHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | Android Asynchronous Http Client
3 | Copyright (c) 2014 Aymon Fournier
4 | http://loopj.com
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | package com.loopj.android.http;
20 |
21 | import org.apache.http.Header;
22 | import org.apache.http.HttpHost;
23 | import org.apache.http.HttpRequest;
24 | import org.apache.http.HttpResponse;
25 | import org.apache.http.HttpStatus;
26 | import org.apache.http.ProtocolException;
27 | import org.apache.http.client.CircularRedirectException;
28 | import org.apache.http.client.params.ClientPNames;
29 | import org.apache.http.client.utils.URIUtils;
30 | import org.apache.http.impl.client.DefaultRedirectHandler;
31 | import org.apache.http.impl.client.RedirectLocations;
32 | import org.apache.http.params.HttpParams;
33 | import org.apache.http.protocol.ExecutionContext;
34 | import org.apache.http.protocol.HttpContext;
35 |
36 | import java.net.URI;
37 | import java.net.URISyntaxException;
38 |
39 | /**
40 | * Taken from StackOverflow
41 | *
42 | * @author Aymon Fournier, aymon.fournier@gmail.com
43 | * @see https://stackoverflow.com/questions/3420767/httpclient-redirecting-to-url-with-spaces-throwing-exception
44 | */
45 | class MyRedirectHandler extends DefaultRedirectHandler {
46 |
47 | private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
48 | private final boolean enableRedirects;
49 |
50 | public MyRedirectHandler(final boolean allowRedirects) {
51 | super();
52 | this.enableRedirects = allowRedirects;
53 | }
54 |
55 | @Override
56 | public boolean isRedirectRequested(
57 | final HttpResponse response,
58 | final HttpContext context) {
59 | if (!enableRedirects) {
60 | return false;
61 | }
62 | if (response == null) {
63 | throw new IllegalArgumentException("HTTP response may not be null");
64 | }
65 | int statusCode = response.getStatusLine().getStatusCode();
66 | switch (statusCode) {
67 | case HttpStatus.SC_MOVED_TEMPORARILY:
68 | case HttpStatus.SC_MOVED_PERMANENTLY:
69 | case HttpStatus.SC_SEE_OTHER:
70 | case HttpStatus.SC_TEMPORARY_REDIRECT:
71 | return true;
72 | default:
73 | return false;
74 | } //end of switch
75 | }
76 |
77 | @Override
78 | public URI getLocationURI(
79 | final HttpResponse response,
80 | final HttpContext context) throws ProtocolException {
81 | if (response == null) {
82 | throw new IllegalArgumentException("HTTP response may not be null");
83 | }
84 | //get the location header to find out where to redirect to
85 | Header locationHeader = response.getFirstHeader("location");
86 | if (locationHeader == null) {
87 | // got a redirect response, but no location header
88 | throw new ProtocolException(
89 | "Received redirect response " + response.getStatusLine()
90 | + " but no location header"
91 | );
92 | }
93 | //HERE IS THE MODIFIED LINE OF CODE
94 | String location = locationHeader.getValue().replaceAll(" ", "%20");
95 |
96 | URI uri;
97 | try {
98 | uri = new URI(location);
99 | } catch (URISyntaxException ex) {
100 | throw new ProtocolException("Invalid redirect URI: " + location, ex);
101 | }
102 |
103 | HttpParams params = response.getParams();
104 | // rfc2616 demands the location value be a complete URI
105 | // Location = "Location" ":" absoluteURI
106 | if (!uri.isAbsolute()) {
107 | if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
108 | throw new ProtocolException("Relative redirect location '"
109 | + uri + "' not allowed");
110 | }
111 | // Adjust location URI
112 | HttpHost target = (HttpHost) context.getAttribute(
113 | ExecutionContext.HTTP_TARGET_HOST);
114 | if (target == null) {
115 | throw new IllegalStateException("Target host not available " +
116 | "in the HTTP context");
117 | }
118 |
119 | HttpRequest request = (HttpRequest) context.getAttribute(
120 | ExecutionContext.HTTP_REQUEST);
121 |
122 | try {
123 | URI requestURI = new URI(request.getRequestLine().getUri());
124 | URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
125 | uri = URIUtils.resolve(absoluteRequestURI, uri);
126 | } catch (URISyntaxException ex) {
127 | throw new ProtocolException(ex.getMessage(), ex);
128 | }
129 | }
130 |
131 | if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
132 |
133 | RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
134 | REDIRECT_LOCATIONS);
135 |
136 | if (redirectLocations == null) {
137 | redirectLocations = new RedirectLocations();
138 | context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
139 | }
140 |
141 | URI redirectURI;
142 | if (uri.getFragment() != null) {
143 | try {
144 | HttpHost target = new HttpHost(
145 | uri.getHost(),
146 | uri.getPort(),
147 | uri.getScheme());
148 | redirectURI = URIUtils.rewriteURI(uri, target, true);
149 | } catch (URISyntaxException ex) {
150 | throw new ProtocolException(ex.getMessage(), ex);
151 | }
152 | } else {
153 | redirectURI = uri;
154 | }
155 |
156 | if (redirectLocations.contains(redirectURI)) {
157 | throw new CircularRedirectException("Circular redirect to '" +
158 | redirectURI + "'");
159 | } else {
160 | redirectLocations.add(redirectURI);
161 | }
162 | }
163 |
164 | return uri;
165 | }
166 | }
--------------------------------------------------------------------------------