java 使用HttpURLConnection发送数据简单实例
每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字。JAVA使用HttpURLConnection发送POST数据是依靠OutputStream流的形式发送
实现代码:
import java.io.*; import java.net.*; public class PostExample { public static void main(String[] argv) throws Exception { URL url = new URL("http://www.javacourses.com/cgi-bin/names.cgi"); HttpURLConnection cOnnection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); // encode the message String name = "name="+URLEncoder.encode("Qusay Mahmoud", "UTF-8"); String email = "email="+URLEncoder.encode("qmahmoud@javacourses.com", "UTF-8"); // send the encoded message out.println(name+"&"+email); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!