首页 > 开发 > Java > 正文

谈谈Java利用原始HttpURLConnection发送POST数据

2024-07-13 09:55:54
字体:
来源:转载
供稿:网友

这篇文章主要给大家介绍java利用原始httpUrlConnection发送post数据,设计到httpUrlConnection类的相关知识,感兴趣的朋友跟着小编一起学习吧

URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。

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

 

  1. package com.newflypig.demo; 
  2. /** 
  3. * 使用jdk自带的HttpURLConnection向URL发送POST请求并输出响应结果 
  4. * 参数使用流传递,并且硬编码为字符串"name=XXX"的格式 
  5. */ 
  6. import java.io.BufferedReader; 
  7. import java.io.DataOutputStream; 
  8. import java.io.InputStreamReader; 
  9. import java.net.HttpURLConnection; 
  10. import java.net.URL; 
  11. import java.net.URLEncoder; 
  12. public class SendPostDemo { 
  13. public static void main(String[] args) throws Exception{ 
  14. String urlPath = new String("http://localhost:8080/Test1/HelloWorld");  
  15. //String urlPath = new String("http://localhost:8080/Test1/HelloWorld?name=丁丁".getBytes("UTF-8")); 
  16. String param="name="+URLEncoder.encode("丁丁","UTF-8"); 
  17. //建立连接 
  18. URL url=new URL(urlPath); 
  19. HttpURLConnection httpConn=(HttpURLConnection)url.openConnection(); 
  20. //设置参数 
  21. httpConn.setDoOutput(true); //需要输出 
  22. httpConn.setDoInput(true); //需要输入 
  23. httpConn.setUseCaches(false); //不允许缓存 
  24. httpConn.setRequestMethod("POST"); //设置POST方式连接 
  25. //设置请求属性 
  26. httpConn.setRequestProperty("Content-Type""application/x-www-form-urlencoded"); 
  27. httpConn.setRequestProperty("Connection""Keep-Alive");// 维持长连接 
  28. httpConn.setRequestProperty("Charset""UTF-8"); 
  29. //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect 
  30. httpConn.connect(); 
  31. //建立输入流,向指向的URL传入参数 
  32. DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream()); 
  33. dos.writeBytes(param); 
  34. dos.flush(); 
  35. dos.close(); 
  36. //获得响应状态 
  37. int resultCode=httpConn.getResponseCode(); 
  38. if(HttpURLConnection.HTTP_OK==resultCode){ 
  39. StringBuffer sb=new StringBuffer(); 
  40. String readLine=new String(); 
  41. BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8")); 
  42. while((readLine=responseReader.readLine())!=null){ 
  43. sb.append(readLine).append("/n"); 
  44. responseReader.close(); 
  45. System.out.println(sb.toString()); 
  46. }  

JAVA使用HttpURLConnection发送POST数据是依靠OutputStream流的形式发送

具体编码过程中,参数是以字符串“name=XXX”这种形式发送

以上内容就是本文的全部所述,希望本文介绍对大家有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表