GithubHelp home page GithubHelp logo

android-async-http / android-async-http Goto Github PK

View Code? Open in Web Editor NEW
10.6K 10.6K 4.1K 2.99 MB

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Home Page: https://github.com/android-async-http/android-async-http#this-project-is-no-longer-maintained-and-is-currently-deprecated-and-insecure-to-use

License: Apache License 2.0

Java 100.00%
android java

android-async-http's Introduction

Asynchronous Http Client for Android

Build Status

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Changelog

See what is new in version 1.4.11 released on 29th June 2020

https://github.com/android-async-http/android-async-http/blob/1.4.11/CHANGELOG.md

Javadoc

Latest Javadoc for 1.4.11 release are available here (also included in Maven repository):

https://android-async-http.github.io/android-async-http/doc/

Features

  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • HTTP requests happen outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • GET/POST params builder (RequestParams)
  • Multipart file uploads with no additional third party libraries
  • Tiny size overhead to your application, only 60kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Optional built-in response parsing into JSON (JsonHttpResponseHandler)
  • Optional persistent cookie store, saves cookies into your app's SharedPreferences
  • Support sni with Conscrypt on older android device (wiki)

Examples

For inspiration and testing on device we've provided Sample Application.
See individual samples here on Github
To run Sample application, simply clone the repository and run this command, to install it on connected device

gradle :sample:installDebug

Maven

You can now integrate this library in your project via Maven. There are available two kind of builds.

releases, maven central

https://repo1.maven.org/maven2/com/loopj/android/android-async-http/

Maven URL: https://repo1.maven.org/maven2/
GroupId: com.loopj.android
ArtifactId: android-async-http
Version: 1.4.11
Packaging: JAR or AAR

Gradle

repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.loopj.android:android-async-http:1.4.11'
}

development snapshots snapshot might not be published yet

https://oss.sonatype.org/content/repositories/snapshots/com/loopj/android/android-async-http/

Maven URL: https://oss.sonatype.org/content/repositories/snapshots/
GroupId: com.loopj.android
ArtifactId: android-async-http
Version: 1.4.12-SNAPSHOT
Packaging: JAR or AAR

Gradle

repositories {
  maven {
    url 'https://oss.sonatype.org/content/repositories/snapshots/'
  }
}
dependencies {
  implementation 'com.loopj.android:android-async-http:1.4.11-SNAPSHOT'
}

Documentation, Features and Examples

Full details and documentation can be found on the project page here:

https://android-async-http.github.io/android-async-http/

android-async-http's People

Contributors

apersaud avatar bahadirbulduk avatar beartung avatar cbliu avatar cherez avatar clayallsopp avatar condda avatar coreform avatar dadav avatar ebuildy avatar etryp avatar geminiwen avatar grumoon avatar jlopez avatar krschultz avatar ldiqual avatar loopj avatar lucamac avatar lvitti avatar mananshr avatar mkuprionis avatar montdidier avatar p-m-j avatar saeed-rz avatar sayadyan avatar scottanderson avatar smarek avatar sweetlilmre avatar ypogribnyi avatar zxw1962 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-async-http's Issues

ability to add headers easily

I noticed reading through the code that changing the user-agent is exposed, but changing the adding headers is not. That would be awesome.

MessageQueue Exception thrown within Service

I am trying to use android-async-http (1.3.2) within an IntentService and I keep getting an exception thrown from MessageQueue that the thread is dead.

here is a snippet that is throwing the error:

client.get(webService("action/testsid"), new AsyncHttpResponseHandler(){
            @Override public void onSuccess(String response){
                Log.d("test", response);
            }
        });

followed by the logcat

05-22 19:42:40.175: W/MessageQueue(632): Handler (com.loopj.android.http.AsyncHttpResponseHandler$1) {414a6ef0} sending message to a Handler on a dead thread
05-22 19:42:40.175: W/MessageQueue(632): java.lang.RuntimeException: Handler (com.loopj.android.http.AsyncHttpResponseHandler$1) {414a6ef0} sending message to a Handler on a dead thread
05-22 19:42:40.175: W/MessageQueue(632):    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
05-22 19:42:40.175: W/MessageQueue(632):    at android.os.Handler.sendMessageAtTime(Handler.java:473)
05-22 19:42:40.175: W/MessageQueue(632):    at android.os.Handler.sendMessageDelayed(Handler.java:446)
05-22 19:42:40.175: W/MessageQueue(632):    at android.os.Handler.sendMessage(Handler.java:383)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:186)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:139)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpResponseHandler.sendResponseMessage(AsyncHttpResponseHandler.java:221)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:68)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:84)
05-22 19:42:40.175: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:50)
05-22 19:42:40.175: W/MessageQueue(632):    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
05-22 19:42:40.175: W/MessageQueue(632):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-22 19:42:40.175: W/MessageQueue(632):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-22 19:42:40.175: W/MessageQueue(632):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-22 19:42:40.175: W/MessageQueue(632):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-22 19:42:40.175: W/MessageQueue(632):    at java.lang.Thread.run(Thread.java:856)
05-22 19:42:40.245: W/MessageQueue(632): Handler (com.loopj.android.http.AsyncHttpResponseHandler$1) {414a6ef0} sending message to a Handler on a dead thread
05-22 19:42:40.245: W/MessageQueue(632): java.lang.RuntimeException: Handler (com.loopj.android.http.AsyncHttpResponseHandler$1) {414a6ef0} sending message to a Handler on a dead thread
05-22 19:42:40.245: W/MessageQueue(632):    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196)
05-22 19:42:40.245: W/MessageQueue(632):    at android.os.Handler.sendMessageAtTime(Handler.java:473)
05-22 19:42:40.245: W/MessageQueue(632):    at android.os.Handler.sendMessageDelayed(Handler.java:446)
05-22 19:42:40.245: W/MessageQueue(632):    at android.os.Handler.sendMessage(Handler.java:383)
05-22 19:42:40.245: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:186)
05-22 19:42:40.245: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpResponseHandler.sendFinishMessage(AsyncHttpResponseHandler.java:147)
05-22 19:42:40.245: W/MessageQueue(632):    at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:53)
05-22 19:42:40.245: W/MessageQueue(632):    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
05-22 19:42:40.245: W/MessageQueue(632):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-22 19:42:40.245: W/MessageQueue(632):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-22 19:42:40.245: W/MessageQueue(632):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-22 19:42:40.245: W/MessageQueue(632):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-22 19:42:40.245: W/MessageQueue(632):    at java.lang.Thread.run(Thread.java:856)

Any ideas?

memory leak improvement for AsyncHttpRequest?

I ran into a memory leak that might be improved by a one-liner in AsyncHttpRequest::run(...)

When a developers calls AsyncHttpClient::get(...) he passes an AsyncHttpResponseHandler along.
This AsyncHttpResponseHandler is often (I believe) implemented as an internal anonymous class, in for example an Activity.
As it's an inner class it implicitly has a this pointer to it's parent - in this case, the Activity.

This is OK as long as nobody else is keeping a reference to the instance of this response handler.

However, AsyncHttpRequest keeps a reference to the responseHandler, and AsyncHttpClient keeps a reference to the AsyncHttpRequest in it's thread pool.

So in other words, if you implement AsyncHttpResponseHandler as an internal class, the parent class is kept alive until the thread pool overwrites your AsyncHttpRequest with a new one. Which could be quite some time.

I suggest you simply reset responseHandler = null at the end of AsyncHttpRequest::run(...).

You could argue that people shouldn't pass in handlers with implicit parent pointers, and I agree - but then again, there is no need to keep the runnable task around in the pool after it's finished either?

Passing a string entity doesn't attach any data.

I have a JSONObject I am trying to post to a server using the following.

AsyncHttpClient aHC = new AsyncHttpClient();
JSONObject locContainer = new JSONObject();
StringEntity se = new StringEntity("JSON: "+locContainer.toString());
        Log.d(TAG, "se:" + EntityUtils.toString(se));
        aHC.post(null, 
            getString( ... ),
                se,
                "application/x-www-form-urlencoded",
                 new AsyncHttpResponseHandler() { ... });

However the server reports that the data being passed is not there.
Information posted via javascript like this

$.ajax({
    type: "POST",
    url: "..,",
    headers: {
            ...
        },
        data: $.evalJSON($('#test_data').val()),
        success: function(data){
            $('#location_results').html(formatJson(data));
        },
}); 

does show the correct data posted.

The server I am working with is not of my design and I am still trying to grok it. (Not to mention learning php in the process.) So it isn't unreasonable that I have screwed up somewhere, however since it works just fine using the javascript test I suspect I am either using the library incorrectly, or I have stumbled upon a bug.

Make timeouts configurable

James, thank you for great library! I've moved from iOS with it's callbacks and impressed that your lib allows me to avoid using abusive threads.

Therefore, I've found issue in your code:


private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;

    ConnManagerParams.setTimeout(httpParams, socketTimeout);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);

So the timeout settings is not accessible even through subclassing.

Moreover,

    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);

Obviously looks like bug because of too short CONNECTION timeout for 10 seconds. Imagine that some people may want to download not only short requests, but also pictures and video...

I'm new in Java, so excuse me if I'm wrong and do not see way to tune it.

setCredentials doesn't work

AsyncHttpClient client = new AsyncHttpClient();

((DefaultHttpClient)client.getHttpClient()).getCredentialsProvider()
   .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

RequestParams params = new RequestParams();

 params.put("user[photo]", new File("pic.jpg")); // Upload a File

 client.post("http://myendpoint.com", params, null);

Getting A Response; Error 401

Binary support

The onSuccess callback passes a String. Are there any plans to support binary responses? I have modifications to your source that would return a byte[], but that changes the api.

Additional Information in AsyncHttpResponseHandler

It's posible I'm missing something, but I don't see anyway to get any additional information bout the request's response.

I'm specifically needing two things:

  • HTTP Status Code in both onSuccess and onError: Casting the throwable in onError to HttpResponseException will let me call getStatusCode(), but this really isn't the cleanest way to go about it
  • Response bodies in onError: RESTful API's frequently send back a response message, along with an HTTP error code.

Bonus: A way to fetch HTTP Response headers in both methods.

ConnectionTimeout not set

I was testing the use of this library when on a network that isn't connected to the host. It was taking a long time to timeout and I found that by adding:

HttpConnectionParams.setConnectionTimeout(httpParams, socketTimout);

to the AsyncHttpClient constructor after the call to setSoTimeout it takes care of this issue.

MultiDownload support

I am working on a project, for which I have added multidownload functionality (downloading of multiple files and firing a single onSuccess event). Currently the code I have is integrated quite tightly with the rest of my project, but I intend to decouple it. It is kind of an edge use case and maybe doesn't belong in this library (for bloat reasons?), but I could put it together in a pull request if the consensus was that it would be a welcome addition.

Can add Basic Auth, but cannot remove it

There is a mechanism to allow users to add credentials. Added in 1.4.0.

    /**
     * Sets basic authentication for the request. Uses AuthScope.ANY. This is the same as
     * setBasicAuth('username','password',AuthScope.ANY) 
     * @param username
     * @param password
     */
    public void setBasicAuth(String user, String pass){
        AuthScope scope = AuthScope.ANY;
        setBasicAuth(user, pass, scope);
    }

   /**
     * Sets basic authentication for the request. You should pass in your AuthScope for security. It should be like this
     * setBasicAuth("username","password", new AuthScope("host",port,AuthScope.ANY_REALM))
     * @param username
     * @param password
     * @param scope - an AuthScope object
     *
     */
    public void setBasicAuth( String user, String pass, AuthScope scope){
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user,pass);
        this.httpClient.getCredentialsProvider().setCredentials(scope, credentials);
    }

Since the library provides convenience methods to add credentials I believe there should be a mechanism to easily remove them as well.

Assist with marginal coverage

Firstly, although I have lots of years of Unix, 4GL, and recently .NET, javascript and php skills, I'm a novice java/android coder. I'm looking for some help with my android app that's running in aerobatic aircraft operating on the fringe of mobile coverage, sending packets of GPS position data to my server from where, in a separate ground-based web app I'm displaying the flight in near real-time.
I quickly found that synchronous http caused the app to hang, so was delighted to find your AsyncHttpClient which goes a long way to resolving my problems. I'm monitoring the onSuccsees response before sending the next packet, stopping the send when the un-responded queue of packets gets to an arbitrary count of three.

When the phone in the aircraft regains a signal signal after it has gone out of range for longish periods of 30 seconds to a few minutes, I find that it sometimes transmits some or all of the queued packets. Sometimes it transmits none. With different management of the queue, sending "blind" without monitoring the onSuccess, I found that occasionally the app hangs completely. I assume that's due to some overflow of backed-up requests.
I don't understand how AsyncHttpClient handles the out of range situation, and my java skills are not really up to examining the source code.
Testing is a challenge as I am not able to observe the app when it's running, it being strapped out of sight in the aircraft and me being on the ground!
Would it be possible, please, for you to provide a high level schematic of how queues of un-processed requests are handled, so I can incorporate appropriate logic in my app?

Callback on cancellation

It would be nice if a request that got cancelled by the user would still execute the onFailure method (or a dedicated callback). Preferably using a dedicated exception / error code. That allows error handling to be centralized.

Also, on another platform I worked with it was possible to get (the equivalents of) onSuccess / onFailure messages after cancellation, because of the asynchronous messages being used. If that is the case here too, then it's even more important to have this feature. Otherwise it would be possible to cancel the request manually, run your cancellation handler manually, then suddenly get an onSuccess from the presumedly cancelled connection!

Thanks for the library!

It seems can't work ,i got a issue like this:

java.net.UnknownHostException: www.baidu.com
at java.net.InetAddress.lookupHostByName(InetAddress.java:497)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
at java.net.InetAddress.getAllByName(InetAddress.java:256)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:140)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:363)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:65)
at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:84)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:50)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:444)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)

Did I miss some settings ???

Control / disable retry attempts?

Is there a way to control the automatic retry behavior? I would prefer that it only try retrying twice as many of my URLs are time-sensitive and will ultimately fail after some time has passed. I don't see any way to do this... ideas?

cookie store is not getting updated

When i m retrieving new pages thru client object, the corresponding cookiestore is not updated with the cookies sent by server. am i missing something? is there something extra needs to be done??

Add utility subclasses of SSLSocketFactory

Two additional subclasses of SSLSocketFactory may be of help to the library users.

  1. AllAcceptingSSLSocketFactory - An implementation that accepts all certificates including self generated untrusted ones. It helps with dev servers.
  2. AdditionalKeyStoresSSLSocketFactory - An implementation that adds additional user provided keystores to the android default keystore set.

Please see the discussion thread on SO - http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/4837230 See answers by Daniel and emmby.

I can make a pull request if you think it is worth adding.

StackOverflow during PUT-request in 1.3.1 version

public void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        put(null, params, responseHandler);
}

Error was in this part of AsyncHttpClient.java
Update: Thanks that fixed in repo already.

Sorry for duplicate of #11.

StackOverflowError

I'm trying to upload a Bitmap (grabbed from Camera). The Bitmap returned from the Camera intent is displayed on the screen so I know there is data to send. Get StackOverflowError at AsyncHttpClient.put (Unknown Source).

onActivityResult
Bitmap b = (Bitmap) data.getExtras().get("data");
profilePhoto.setImageBitmap(b);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(CompressFormat.PNG, 85, bos);
onPhotoTaken(baos.toByteArray());

onPhotoTaken(byte[] ba)
AsyncHttpClient ahc = new AsyncHttpClient();
PersistentCookieStore pcs = new PersistentCookieStore(this);
RequestParams rp = new RequestParams();
rp.put("photo", new ByteArrayInputStream(ba));
ahc.setCookieStore(pcs);
c.put("php script address", rp, new AsyncHttpResponseHandler() {
@OverRide
public void onSuccess(String result) {
//Success Toast
}
@OverRide
public void onFailure(Throawable e) {
//Failure Toast
}
});

Probably something I'm doing wrong but can't spot it my side

Add onProgress() for BinaryHttpResponseHandler

It would be great if the BinaryHttpResponseHandler has something like onProgressUpdate to let the developers show for example a ProgressDialog Bar with the percentage of the Downloaded data.

I could make in charge of this feature if you want.

Thanks in advance!!!

Include Javadoc with each new release of the library.

It would be nice if you included a .zip file containing the .jar library, a .jar.properties file and the Javadoc with each release. Doing so will make it much easier to get the Javadoc linked in Eclipse.

Obviously most developers can pull down the source and build the Javadoc themselves, however it would be easier for more novice developers to use the Javadoc if it were just included in the download.

Example ZIP contents:

android-async-http-1.4.1.zip
    - android-async-http.jar
    - android-async-http.jar.properties
    - docs/html/...

Example .properties file:

# Place this .properties file in your libs/ directory with the
# library.
doc=../docs/html

upload image always fail!

Hi, I use this client to upload a image, but always got a exception. My code like this:

String url = "https://myweb/album_upload";
RequestParams p = new RequestParams();
InputStream stream = new FileInputStream(new File("/mnt/sdcard/upload.jpg"));
p.put("desc", desc);
p.put("image", stream);
client.post(context, url, apiHeaders(), p, "multipart/form-data", handler);

and I got the log here:

W/System.err(24274): java.io.IOException: read failed: EBADF (Bad file number)
W/System.err(24274): at libcore.io.IoBridge.read(IoBridge.java:432)
W/System.err(24274): at java.io.FileInputStream.read(FileInputStream.java:179)
W/System.err(24274): at com.loopj.android.http.SimpleMultipartEntity.addPart(SimpleMultipartEntity.java:112)
W/System.err(24274): at com.loopj.android.http.SimpleMultipartEntity.addPart(SimpleMultipartEntity.java:97)
W/System.err(24274): at com.loopj.android.http.RequestParams.getEntity(RequestParams.java:199)
W/System.err(24274): at com.loopj.android.http.AsyncHttpClient.paramsToEntity(AsyncHttpClient.java:515)
W/System.err(24274): at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:373)

so could you help me out of it? I test this code in android 4.0.3 and android 2.3.3, result the same

Thanks

onFailure getting called twice while using JsonHttpResponseHandler

My onFailure method is getting called twice when I get a ConnectException. Looking at the code, it looks like this is because:

In JsonHttpResponseHandler:92 super.handleFailureMessage(e, responseBody) calls onFailure(Throwable error, String content)

And also further down, In JsonHttpResponseHandler:102, 105 calls onFailure(Throwable error, String content) explicitly.

Ideally, onFailure should be called only once. May be JsonHttpResponseHandler:handleFailureMessage() need not call the super method.

Please fix. Or shall I submit a patch?

cancelRequests

How to cancel request? use AsyncHttpClient.cancelRequests, not working

NullPointerException: Status code 204 No Content

java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:112)
at org.json.JSONTokener.nextValue(JSONTokener.java:90)
at com.loopj.android.http.JsonHttpResponseHandler.parseResponse(JsonHttpResponseHandler.java:81)
at com.loopj.android.http.JsonHttpResponseHandler.handleSuccessMessage(JsonHttpResponseHandler.java:67)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:173)
at com.loopj.android.http.AsyncHttpResponseHandler$1.handleMessage(AsyncHttpResponseHandler.java:85)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4385)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at dalvik.system.NativeStart.main(Native Method)

Expose the RetryHandler

Please add a getter and setter for the RetryHandler so we can override the default handler.

Or alternatively, create public methods which allow us to change the default handler's settings. I'd like to be able to change the max retries and modify the the blacklisted/whitelisted exceptions.

I realize you can get to it through the getHttpClient method and casting to DefaultHttpClient, but it's somewhat cumbersome.

Encode (or serialize) request body

I guess RequestParams is the best place to do this. To use with a JSON based REST API, I need to send JSON encoded request body with 'application/json' header. I can send the header with client.addHeader() but cannot encode request body. Will try to do it myself but just wanted to make sure if I'm on the right track.

Forever loop while host is not found

Tried your library. Nice. I've wanted to write something like you by myself.
Anything works great except that when host is not found the get/post request loop for forever.
No notifications, no cancel.

Small one bad thing...

no support http 304

User HttpConnectionUrl, no problem.
But, use AndroidAsyncHttp lib,
AddHeader("if-Modified-Since", "Date"), return NullPointerException

Request not callback onSuccess() handler

I trying to call the request (get) in fragment to a simple rest service which I've tested it by tradional way and everything is fine.
But when I calling using asyn http lib it's only callback to onStart but after that, nothing occur. Not even onFailure

This might be an issue with android 4.1 and master-details nav style.

Thanks for any response.

AsyncHttpClient images

Greetings,

How to update an image from AsyncHttpClient?

Here's my code:

@Override
public void onSuccess(String response) {                
    Bitmap bm = BitmapFactory.decodeFile(response);

    ImageView imgView = (ImageView)findViewById(R.id.imageView1);
    imgView.setImageBitmap(bm);
}

I also tried this:

            @Override
            public void onSuccess(String response) {
                Drawable d = null;
                Object content=response.getBytes();
                InputStream is = (InputStream)content;
                d = Drawable.createFromStream(is, "src");

                ImageView imgView= (ImageView)findViewById(R.id.imageView1);
                imgView.setImageDrawable(d);
            }

But the image always appears blank ;( I need some way of converting the String response into a drawable...

I saw from another issue that there are plans to transmit binary data and not just Strings?

Any insight greatly appreciated.

Getting headers?

Hello,

I'm using android-async-http for a while but now I'm facing a problem. I want also to know the headers of the HTTP response. Is it possible?

I've been digging into the source and I can't figure out a way of doing it. Do I have to add additional onSuccess() methods with extra parameter?

Thanks!

Error on Web Page Example

Example text should match the example in the source repository:

Incorrect (JSONArray response should be timeline)

 public void onSuccess(JSONArray response) {
            // Pull out the first event on the public timeline
            JSONObject firstEvent = timeline.get(0);
            String tweetText = firstEvent.getString("text");

            // Do something with the response
            System.out.println(tweetText);
    }

Correct

 public void onSuccess(JSONArray timeline) {
            try {
                JSONObject firstEvent = (JSONObject)timeline.get(0);
                String tweetText = firstEvent.getString("text");

                // Do something with the response
                System.out.println(tweetText);
            } catch(JSONException e) {
                e.printStackTrace();
            }
        }

NPE in HttpClient on http status 204

Hi,

While using your lib i got a "NPE in HttpClient" error logged in Loggcat on a request that was always ending in a failure.
As the same request was working perfectly fine when i was testing it myself i took a look on your code and found the following code in AsyncHttpRequest :


try {
        makeRequest();
        return;
    } catch (IOException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
    } catch (NullPointerException e) {
        // there's a bug in HttpClient 4.0.x that on some occasions causes
        // DefaultRequestExecutor to throw an NPE, see
        // http://code.google.com/p/android/issues/detail?id=5255
        Log.e("AsyncHttpRequest", "NPE in HttpClient", e);
        cause = new IOException("NPE in HttpClient" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
}

As i wasn't using any proxy, i continued deeper in the code and found that theHttpResponseInterceptor sets to the httpClient in the AsyncHttpClient constructor wasn't testing null HttpEntity (which can actually happens when no response is sent | http status 204).

I would suggest to add an early return when the entity is null which wouldn't raise any NPE.


httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
    public void process(HttpResponse response, HttpContext context) {
        final HttpEntity entity = response.getEntity();
        // Here entity is null if the http status of the request was 204, no response
        // if (entity == null) {
        //     return;
        // }
        final Header encoding = entity.getContentEncoding();
        if (encoding != null) {
            for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                    response.setEntity(new InflatingEntity(response.getEntity()));
                    break;
                }
            }
        }
    }
});

missing properties in build.xml

looks like build.xml is expecting local.properties file with sdk.dir and version.num which is not included. Might be nice to mention that in the' building from source' section.

Cookies do not appear to be being sent

I created a BasicClientCookie, added it to a PersistentCookieStore, followed by setting the CookieStore in the AsyncHttpClient but the Cookie field does not appear to be set in the request. I'm not sure if I'm missing something.

cancelRequests not working!!!

Executed the cancelRequests Method! But onSuccess be called. Why?

my code:

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.loopj.android.http.*;

public class HttpClientActivity extends Activity {

    private TextView textView = null;
    private Button btn = null;
    ProgressDialog progressDialog = null;
    AsyncHttpClient client = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpclient_app);
        textView = (TextView)findViewById(R.id.textView1);
        btn  = (Button)findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {


            client = new AsyncHttpClient();
            client.get("http://www.yahoo.co.jp", new AsyncHttpResponseHandler() {

                @Override
                public void onStart() {
                    client.cancelRequests(HttpClientActivity.this, true);
                }

                @Override
                public void onSuccess(String response) {
                    // Why called the onSuccess method?
                    textView.setText(response);
                    System.out.println(response);
                }

                @Override
                public void onFailure(Throwable throwable) {
                    System.out.println(throwable.toString());
                }
            });

            }
        });

    }

}

Why is SimpleMultipartEntity non-repeatable?

On about 10% of my requests when I'm uploading an image file in a PUT/POST, I am getting a ClientProtocolException stemming from a NonRepeatableRequestException. I'm not sure why the SimpleMultipartEntity object is trying to be re-read (doesn't look like AsyncHttpRequest's executionCount is incrementing above 1), but since SimpleMultipartEntity's isRepeatable returns 'false', then this exception will be thrown if it tries to repeat.

I'm wondering why it is returning false? I am not an expert in input/output streams, but it seems to me that there is nothing in SimpleMultipartEntity that would require returning false... am I missing something?

On a deeper level I need to figure out why the entity is trying to be repeated at all...

Possible switch from Apache Http Client to HttpUrlConnection

Has this ever been discussed ?

Android seems to be "deprecating" ( not really deprecating, but couldn't find a better word ) apache http client in favor of HttpUrlConnection. See the following quote from the android developers blog ( http://android-developers.blogspot.com/2011/09/androids-http-clients.html ):

"Which client is best?
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward."

This is obviously a huge amount of work, but if it provides speed improvements as well as battery life, is it worth it?"

Didn't know where else to post this, sorry for cluttering up the issues.

Handle nullpointer on JsonHttpResponseHandler.parseResponse

It seems there are some issues on the library.

Infact, on some scenarios, I get a nullpointerexception caused by ( I think ) responseBody being null.. In the parseResponse code we should also handle nullpointerException. In this way this problem should go away.

I attach here the stacktrace:

java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at com.loopj.android.http.JsonHttpResponseHandler.parseResponse(JsonHttpResponseHandler.java:81)
at com.loopj.android.http.JsonHttpResponseHandler.handleSuccessMessage(JsonHttpResponseHandler.java:67)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:173)
at com.loopj.android.http.AsyncHttpResponseHandler$1.handleMessage(AsyncHttpResponseHandler.java:85)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.