【发布时间】:2013-08-07 14:55:25
【问题描述】:
在我的 android 应用程序中,我需要连接到互联网以检查时间。这个 sn-p 在移动网络和未启用代理的 WiFi 网络中运行良好:
public class MyTimeGetterTask {
@Override
protected Long doInBackground(Void... params) {
WebTimeSntpClient client = new WebTimeSntpClient();
if (client.requestTime("time-d.nist.gov", 3000)) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime()
- client.getNtpTimeReference();
return now;
}
else {
return null;
}
}
}
WebTimeSntpClient的核心元素如下:
public class WebTimeSntpClient {
public boolean requestTime(String host, int timeout) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
...
socket.send(request);
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
...
} catch (IOException ex) {
return false;
} finally {
if (socket != null) {
socket.close();
}
}
return true;
}
}
但是,当我在办公室并且 WiFi 要求我配置代理时(我在设置中通过长按网络然后单击“修改网络”来配置代理 - 从 Android API 级别 17 开始)连接失败。
现在我在互联网上查找了很多关于代理的非常好的帖子,尤其是在 SO 上,但绝对没有一个人似乎回答了这个(对我而言)非常简单的问题:
如何强制我的应用程序使用已在设置中配置的代理?
相反,他们专注于更高级的问题,例如:
- How to GET a proxy from the system
- How to SET ip information to the system yourself
- 以及更多关于如何使 Play 商店中的现有应用程序使用代理的更多信息
再次:我想强调这不是我的意图,我只是想让我的应用程序连接到互联网,无论如何。有一些System.useWifiProxyIfAvailable(true) 方法吗?我确定我一定错过了这里的某个帖子...
【问题讨论】:
-
您的代理可能只允许 HTTP/HTTPS 连接
-
嗯,听起来不错,所以你是说我没有通过 http 连接?我将如何解决这个问题?谢谢
-
WebTimeSntpClient: Sntp != HTTP
-
感谢您的澄清。您是否知道“重新打包”我的数据以使其通过的方法?我不得不说我确实想坚持使用 NTP,而且我不是代理的管理员......