基本上,我正在尝试通过 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();
编辑:没有抛出异常,因为代码执行得很好,请求可能不是服务器预期的格式?