use*_*906 6 url proxy android httpurlconnection android-volley
我是Volley Networking Library(Android版)的新手.我观察到Request函数将URL作为参数而不是服务器名称和端口.如果我提到服务器名称和端口,有没有办法让Volley请求通过我选择的代理服务器?
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
Run Code Online (Sandbox Code Playgroud)
我知道我们可以在构建URL时使用服务器和端口信息,但除此之外还有其他方法可以确保请求通过我们提到的代理吗?
例如: 如何使HttpURLConnection使用代理? 这是一种确保HttpURLConnection使用代理的方法.我正在为Volley寻找类似的答案.
Pra*_*een 13
Volley没有提供任何直接设置代理的方法,但有一种方法.
创建一个扩展HurlStack的自定义类,比如ProxiedHurlStack
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import com.android.volley.toolbox.HurlStack;
public class ProxiedHurlStack extends HurlStack {
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
// Start the connection by specifying a proxy server
Proxy proxy = new Proxy(Proxy.Type.HTTP,
InetSocketAddress.createUnresolved("192.168.1.11", 8118));//the proxy server(Can be your laptop ip or company proxy)
HttpURLConnection returnThis = (HttpURLConnection) url
.openConnection(proxy);
return returnThis;
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用以下命令初始化队列:
mRequestQueue = Volley.newRequestQueue(context, new ProxiedHurlStack());
Run Code Online (Sandbox Code Playgroud)
礼貌:http://d.hatena.ne.jp/esmasui/20130613/1371126800
小智 5
如果用户在系统级别设置了代理(例如,用于wifi连接的代理主机),那么您将不会在您的应用程序中明确知道这一点。为了解决这个问题,我还扩展了HurlStack以使用第一个预配置的代理:
public class ProxyHurlStack extends HurlStack {
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
final HttpURLConnection urlConnection;
Proxy proxy = null;
try {
proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
} catch (Exception e) {
Ln.e(e, e.getMessage());
}
if (proxy == null) {
urlConnection = (HttpURLConnection) url.openConnection();
} else {
urlConnection = (HttpURLConnection) url.openConnection(proxy);
}
return urlConnection;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3060 次 |
最近记录: |