java 使用HttpURLConnection发送数据简单实例

2025-05-29 0 66

java 使用HttpURLConnection发送数据简单实例

每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字。JAVA使用HttpURLConnection发送POST数据是依靠OutputStream流的形式发送

实现代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
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();

}

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/jamesjxin/article/details/7857939

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java 使用HttpURLConnection发送数据简单实例 https://www.kuaiidc.com/116247.html

相关文章

发表评论
暂无评论