我的代码在Android5.0或更高版本上运行正常。但在Android4.1.1中,它抛出了java.net.SocketTimeoutException: SSL握手超时。
URL url;
HttpURLConnection connection = null;
String charset = "UTF-8";
String accessToken = "";
try {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
postParameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
postParameters.add(new BasicNameValuePair("grant_type", CLIENT_CREDENTIALS_GRANT_TYPE));
//Create connection
url = new URL(ACCESS_TOKEN_URL);
connection = (HttpURLConnection)url.openConnection();
connection.setReadTimeout( 10000 /*milliseconds*/ );
connection.setConnectTimeout( 15000 /* milliseconds */ );
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(getQuery(postParameters).getBytes(charset));
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
InputStream is = null;
if(responseCode==HttpStatus.SC_OK) {
is = connection.getInputStream();
}
else{
is = connection.getErrorStream();
}
Log.d(TAG, "responseCode: "+responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
String jsonResult = sb.toString();
JSONObject jsonObject = new JSONObject(jsonResult);
if(responseCode==HttpStatus.SC_OK){
accessToken = jsonObject.getString("access_token");
SettingsPreference.setAccessToken(accessToken);
Log.d(TAG, "access token: "+accessToken);
}
else {
accessToken = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
}
我已经做了很多研究,这非常令人沮丧。我哪里出问题了?这是服务器问题吗?非常感谢您的帮助。
发布于 2018-07-28 02:06:38
在较低的sdk级别上使用TrustManager?
您的旧设备上的受信任证书可能不是最新的。如果设备处于某个sdk级别,您可以尝试实现和使用SimpleTrust。
一个简单的库,用于信任自签名或未正确签名的域。但在你的情况下,我认为只为你的域做一个例外,而不检查某个sdk级别下的认证是很方便的。
此代码库使用TrustManager对某些认证/域进行例外处理。如果您要使用它,请确保正确使用它,因为Google Play可能不会接受您的应用程序更新/发布。
请看我在this上的回答其他问题。
https://stackoverflow.com/questions/30889933
复制相似问题