我有以下代码用于连接到网址。我的问题是,当我在调试中运行它时,我看到connected = false
并且我尝试设置的其他参数都没有工作(例如timeout
)。谁能帮我这个?我做错了什么?
在有人要求之前,我的清单有互联网许可。
private static class SyncOperation extends AsyncTask<String, String, Integer> {
@Override
protected Integer doInBackground(String... params) {
HttpsURLConnection urlConnection = null;
URL url = null;
String msg = "Good";
int code = 0;
try {
System.setProperty("http.keepAlive", "false");
url = new URL("https://www.google.com");
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
} catch (MalformedURLException e) {
msg = "Bad MalformedURLException";
e.printStackTrace();
Log.e("HTTPS", e.getMessage());
} catch (IOException e) {
msg = "Bad IOException";
e.printStackTrace();
Log.e("HTTPS", e.getMessage());
} finally {
urlConnection.disconnect();
Log.d("HTTPS", msg);
Log.d("HTTPS", "diconnected");
}
return code;
}
@Override
protected void onPostExecute(Integer code) {
super.onPostExecute(code);
Toast t = Toast.makeText(mContext, code.toString(), Toast.LENGTH_SHORT);
t.show();
}
}
答案 0 :(得分:2)
您只是在配置连接,但没有连接它。方法url.openConnection()
的名称具有误导性:它不会打开连接。它只给你一个最初没有连接的连接对象。
您需要调用导致连接连接的任何方法,例如connect()
换句话说,尝试对您的连接实际执行某些操作,例如阅读内容并将其写入System.out.println()
。这将自动打开连接。