问题
I'm developing an Android app that utilizes a third-party jar. I want to monitor and possibly modify the HTTP requests issued by that library. Under iOS, I can do that by registering a custom NSURLProtocol
class that can inspect and manipulate any network requests that happen in the app's process.
Is there anything similar for Android? I admit, I am new to Android development, but have been unable to find a working solution to this problem.
I don't have the source for this jar, and I can't rely on decompiling it.
A couple of things I've explored:
- Android ContentProvider. Won't work, since the solution must support "http://" requests, not "content://" requests.
- Creating a custom
org.apache.http.impl.client.DefaultHTTPClient
class. (This is the underlying networking class used for the requests I'm after.) Seems that this won't work, since Android has cached the system version of this class and always loads that instead of mine, even though it is set higher in the load order.
I've looked over the Apache HTTP library pretty well, and while it has all sorts of things like HttpRequestInterceptor
, HttpResponseInterceptor
classes, that doesn't do me much good, since the library instantiates a DefaultHTTPClient
instance and assigns it to a private member within a private method that I don't have access to.
My ultimate goal here is to monitor and alter these requests for unit testing purposes. I don't want the real requests to be issued; I want to supply a mock response.
回答1:
You are unfortunately out of luck: there is no app-wide interception framework of that sort available to Android apps.
My suggestion would be to setup a proxy that intercepts the requests and supplies your mock response.
来源:https://stackoverflow.com/questions/10148926/what-is-androids-equivalent-for-nsurlprotocol-from-the-ios-sdk