所以我一直试图通过我的Android应用程序使用HttpURLconnection连接到IP Camera(型号:Foscam fI9821w v2)。
正如在Foscam论坛上所说,我需要使用的URL的格式如下:" http://ipaddress:port/cgibin/CGIProxy.fcgicmd=snapPicture2&usr=admin&pwd=xxx"。
以下是我的代码尝试连接到相机并检索流的方法:
public InputStream httpRequest(String link, String usr, String pwd) {
InputStream is = null;
URL url = null;
try {
url = new URL(link);
System.out.println("Attempting to connect to: " + url.toString());
// basic auth
String userpass = usr + ":" + pwd;
int flags = Base64.URL_SAFE | Base64.NO_WRAP;
byte[] authEncBytes = userpass.getBytes();
String authStringEnc = Base64.encodeToString(authEncBytes, flags);
String basicAuth = "Basic " + Base64.encode(userpass.getBytes(), flags);
System.out.println("*** basicAuth: " + basicAuth);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 5.0; SM-G900F Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.105 Mobile Safari/537.36");
urlConnection.setRequestProperty("Authorization", "Basic" + basicAuth);
//urlConnection.setDoInput(true);
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
is = urlConnection.getInputStream();
}
System.out.println("WHAT DOES THIS SAY: " + urlConnection.toString());
System.out.println("RESPONSE: " + responseCode);
int rc = urlConnection.getResponseCode();
urlConnection.disconnect();
if ((rc == 401) || (rc == 403) || (rc == 404) || (rc >= 500)){
Log.i(TAG, String.valueOf(rc));
} else {
Log.i(TAG, "SUCCESS!");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
我使用上面的网址格式,但我假设我可以删除"& usr = admin& pwd = xxx"从URL的末尾,因为我使用setRequestProperty进行身份验证? (如果我错了,请纠正我)。我已经在另一个应用程序(iSpy)中尝试过该URL,但它确实有效,但它有"& usr = admin& pwd = xxx"在它的最后。 无论如何,我总是得到以下错误:
java.net.SocketTimeoutException: failed to connect to /192.168.0.15 (port 80) after 5000ms
其次是:
java.io.IOException: BufferedInputStream is closed
我已经在互联网上搜索了一段时间,试图弄清楚我做错了什么,并且我多次修改了我的代码。任何人都可以帮我确定我做错了吗?