URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(8000); connection.setConnectTimeout(8000); InputStream in = connection.getInputStream(); InputStreamReader is = new InputStreamReader(in); BufferedReader reader = new BufferedReader(is); StringBuilder builder = new StringBuilder(); String line ; while((line = reader.readLine())!= null){ builder.append(line); //BufferedReader 不可追加, //而StringBuilder 可以追加 } String result = builder.toString();
向输入流中写入字符串
connection.setRequestMethod("POST"); OutputStream os = connection.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.writeBytes("username=admin&password=123456"); //不确定是否要关闭,可能需要flush(); //////