我的静态方法的每秒 HttpsUrlConnection 请求在 Android 上都会失败
我对静态 HTTPS 连接方法有一个大问题。 每隔一个请求就会失败,并且 HttpsUrlConnection.getResponseCode()
返回 -1
。因此,每一次调用都运行良好,按预期返回数据。
这是我在应用程序的不同角落使用的静态类的方法。我猜想当该方法第一次返回时,有任何东西我没有正确清理,并且任何导致问题的原因都可能通过该方法的第二次调用而被破坏。但我很难找到任何线索。
我目前正在使用此类与具有无效 SSL 证书的主机进行通信。不会在应用程序的最终版本中使用它,但现在我需要省钱。 ;)
public static String makeInvalidHTTPSRequest(String url, String[] postVars, String userName, String userPass, Context ctx) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
StringBuffer sb = new StringBuffer();
String serverAuth = null;
String serverAuthBase64 = null;
StringBuffer urlParameters = new StringBuffer();
InputStream rcvdInputStream = null;
if (checkNetworkAvailability(ctx) == false) {
GeneralMethods.writeLog("Network unavailable", 1, GeneralMethods.class);
return null;
}
SSLContext sc = null;
sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new KTPTrustManager() }, new SecureRandom());
GeneralMethods.writeLog("makeInvalidHTTPSRequest-> " + url + ", " + userName + ", " + userPass, 0, GeneralMethods.class);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new KTPHostnameVerifier());
HttpsURLConnection con = null;
con = (HttpsURLConnection) new URL(url).openConnection();
if (userName != null) {
serverAuth = userName + ":" + userPass;
serverAuthBase64 = KTPBase64.encode(serverAuth.getBytes());
}
try {
String[] tmpPair = null;
con.setRequestMethod("POST");
if (serverAuthBase64 != null)
con.setRequestProperty("Authorization", "Basic " + serverAuthBase64);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (postVars != null) {
for (int i = 0; i < postVars.length; i++) {
tmpPair = postVars[i].toString().split("=");
if (i > 0)
urlParameters.append("&" + tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
else
urlParameters.append(tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
}
con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.toString().getBytes().length));
}
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
if (postVars != null)
wr.writeBytes (urlParameters.toString());
wr.flush();
wr.close();
if (con.getResponseCode() == 200) {
globalRetries = 0;
rcvdInputStream = con.getInputStream();
}
else if (con.getResponseCode() == 401) {
con.disconnect();
GeneralMethods.writeLog("error 401", 2, GeneralMethods.class);
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
else {
GeneralMethods.writeLog("error - connection response code " + con.getResponseCode() + ": " + con.getResponseMessage() + " (length: "+ con.getContentLength() +")\n\n", 1, GeneralMethods.class);
con.disconnect();
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(rcvdInputStream), 8192 );
String line;
while ( ( line = br.readLine() ) != null ) {
sb.append(line);
}
con.disconnect();
con = null;
}
catch(Exception e) {
handleException(e, 2, GeneralMethods.class);
}
GeneralMethods.writeLog("makeInvalidHTTPSRequest: Response is \"" + sb.toString() + "\"\n\n", 0, GeneralMethods.class);
if(con != null) {
con.disconnect();
con = null;
}
if (sb.toString().trim() == "")
return null;
else
return sb.toString();
}
非常感谢您的帮助!
最好的问候
S。
I'm having a big issue with a static HTTPS connection method. Every second request fails and HttpsUrlConnection.getResponseCode()
returns -1
. So every second call works well, returning data as expected.
It's the method of a static class I'm using in different corners of my application. I would guess there is anything I don't clean up correctly when the method returns the first time and that whatever causes a problem might get destroyed through a second call of the method. But I'm having a hard time finding any clues.
I'm currently using this class to talk to hosts with invalid SSL certificates. Not going to use this in the final version of the app, but right now I need to save money. ;)
public static String makeInvalidHTTPSRequest(String url, String[] postVars, String userName, String userPass, Context ctx) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
StringBuffer sb = new StringBuffer();
String serverAuth = null;
String serverAuthBase64 = null;
StringBuffer urlParameters = new StringBuffer();
InputStream rcvdInputStream = null;
if (checkNetworkAvailability(ctx) == false) {
GeneralMethods.writeLog("Network unavailable", 1, GeneralMethods.class);
return null;
}
SSLContext sc = null;
sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new KTPTrustManager() }, new SecureRandom());
GeneralMethods.writeLog("makeInvalidHTTPSRequest-> " + url + ", " + userName + ", " + userPass, 0, GeneralMethods.class);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new KTPHostnameVerifier());
HttpsURLConnection con = null;
con = (HttpsURLConnection) new URL(url).openConnection();
if (userName != null) {
serverAuth = userName + ":" + userPass;
serverAuthBase64 = KTPBase64.encode(serverAuth.getBytes());
}
try {
String[] tmpPair = null;
con.setRequestMethod("POST");
if (serverAuthBase64 != null)
con.setRequestProperty("Authorization", "Basic " + serverAuthBase64);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (postVars != null) {
for (int i = 0; i < postVars.length; i++) {
tmpPair = postVars[i].toString().split("=");
if (i > 0)
urlParameters.append("&" + tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
else
urlParameters.append(tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
}
con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.toString().getBytes().length));
}
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
if (postVars != null)
wr.writeBytes (urlParameters.toString());
wr.flush();
wr.close();
if (con.getResponseCode() == 200) {
globalRetries = 0;
rcvdInputStream = con.getInputStream();
}
else if (con.getResponseCode() == 401) {
con.disconnect();
GeneralMethods.writeLog("error 401", 2, GeneralMethods.class);
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
else {
GeneralMethods.writeLog("error - connection response code " + con.getResponseCode() + ": " + con.getResponseMessage() + " (length: "+ con.getContentLength() +")\n\n", 1, GeneralMethods.class);
con.disconnect();
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(rcvdInputStream), 8192 );
String line;
while ( ( line = br.readLine() ) != null ) {
sb.append(line);
}
con.disconnect();
con = null;
}
catch(Exception e) {
handleException(e, 2, GeneralMethods.class);
}
GeneralMethods.writeLog("makeInvalidHTTPSRequest: Response is \"" + sb.toString() + "\"\n\n", 0, GeneralMethods.class);
if(con != null) {
con.disconnect();
con = null;
}
if (sb.toString().trim() == "")
return null;
else
return sb.toString();
}
Thanks a lot for your help!
Best regards
S.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能会有所帮助:HttpsURLConnection 和间歇性连接
This might be of help: HttpsURLConnection and intermittent connections