java http url post json

Java代码  收藏代码
  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.io.OutputStreamWriter;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6.   
  7. public class Copy_2_of_PostDemo {  
  8.   
  9.     final static String url = "";  
  10.     final static String params = "{\"id\":\"12345\"}";  
  11.   
  12.     /** 
  13.      * 发送HttpPost请求 
  14.      *  
  15.      * @param strURL 
  16.      *            服务地址 
  17.      * @param params 
  18.      *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/> 
  19.      * @return 成功:返回json字符串<br/> 
  20.      */  
  21.     public static String post(String strURL, String params) {  
  22.         System.out.println(strURL);  
  23.         System.out.println(params);  
  24.         try {  
  25.             URL url = new URL(strURL);// 创建连接  
  26.             HttpURLConnection connection = (HttpURLConnection) url  
  27.                     .openConnection();  
  28.             connection.setDoOutput(true);  
  29.             connection.setDoInput(true);  
  30.             connection.setUseCaches(false);  
  31.             connection.setInstanceFollowRedirects(true);  
  32.             connection.setRequestMethod("POST"); // 设置请求方式  
  33.             connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
  34.             connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
  35.             connection.connect();  
  36.             OutputStreamWriter out = new OutputStreamWriter(  
  37.                     connection.getOutputStream(), "UTF-8"); // utf-8编码  
  38.             out.append(params);  
  39.             out.flush();  
  40.             out.close();  
  41.             // 读取响应  
  42.             int length = (int) connection.getContentLength();// 获取长度  
  43.             InputStream is = connection.getInputStream();  
  44.             if (length != -1) {  
  45.                 byte[] data = new byte[length];  
  46.                 byte[] temp = new byte[512];  
  47.                 int readLen = 0;  
  48.                 int destPos = 0;  
  49.                 while ((readLen = is.read(temp)) > 0) {  
  50.                     System.arraycopy(temp, 0, data, destPos, readLen);  
  51.                     destPos += readLen;  
  52.                 }  
  53.                 String result = new String(data, "UTF-8"); // utf-8编码  
  54.                 System.out.println(result);  
  55.                 return result;  
  56.             }  
  57.         } catch (IOException e) {  
  58.             // TODO Auto-generated catch block  
  59.             e.printStackTrace();  
  60.         }  
  61.         return "error"; // 自定义错误信息  
  62.     }  
  63.   
  64.     public static void main(String[] args) {  
  65.         post(url, params);  
  66.     }  
  67.   
  68. }  




备注 

httpUrlConnection.setDoOutput(true);以后就可以使用conn.getOutputStream().write() 
httpUrlConnection.setDoInput(true);以后就可以使用conn.getInputStream().read(); 

get请求用不到conn.getOutputStream(),因为参数直接追加在地址后面,因此默认是false。 
post请求(比如:文件上传)需要往服务区传输大量的数据,这些数据是放在http的body里面的,因此需要在建立连接以后,往服务端写数据。 

因为总是使用conn.getInputStream()获取服务端的响应,因此默认值是true。

posted @   silentmuh  阅读(1699)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
Live2D
欢迎阅读『java http url post json』
  1. 1 Walk Thru Fire Vicetone
  2. 2 爱你 王心凌
  3. 3 Inspire Capo Productions - Serenity
  4. 4 Welcome Home Radical Face
  5. 5 粉红色的回忆 李玲玉
Welcome Home - Radical Face
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : Ben P. Cooper

作曲 : Cooper

Sleep don't visit, so I choke on sun

And the days blur into one

And the backs of my eyes hum with things I've never done

Sheets are swaying from an old clothesline

Was never much but we've made the most

Welcome home

Ships are launching from my chest

Some have names but most do not

If you find one,please let me know what piece I've lost

Heal the scars from off my back

I don't need them anymore

You can throw them out or keep them in your mason jars

I've come home

All my nightmares escaped my head

Bar the door, please don't let them in

You were never supposed to leave

Now my head's splitting at the seams

And I don't know if I can

Here, beneath my lungs

I feel your thumbs press into my skin again

点击右上角即可分享
微信分享提示