基本上,我正在嘗試透過 Android 應用程式連接到 Web 介面。
我成功地使用 HttpClient 向表單發送命令。但是,我想使用這裡推薦的 HttpUrlConnection 來完成此操作http://android-developers.blogspot.com/2011/09/androids-http-clients.html,目的是獲得更快、更節能的連接。
URL url = new URL("http://" + mIpAddress + ":" + mPort + "/command.html"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(URLEncoder.encode("parameter=" + value, "UTF-8"); writer.flush(); writer.close(); os.close(); connection.connect();
編輯:沒有拋出異常,因為程式碼執行得很好,請求可能不是伺服器預期的格式?