温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-21 06:59:47 来源:脚本之家 阅读:125 作者:lqh 栏目:编程语言

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI