随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

使用HttpURLConnection向服务器发送post和get请求

一、使用HttpURLConnection向服务器发送get请求

1、向服务器发送get请求

复制代码
    @Test
publicvoid sendSms() throws Exception{
String message
="货已发到";
message
=URLEncoder.encode(message, "UTF-8");
System.out.println(message);
String path
="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
URL url
=new URL(path);
HttpURLConnection conn
= (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(
5*1000);
conn.setRequestMethod(
"GET");
InputStream inStream
= conn.getInputStream();
byte[] data = StreamTool.readInputStream(inStream);
String result
=new String(data, "UTF-8");
System.out.println(result);
}
复制代码

2、从服务器读取数据    

String message=request.getParameter("message");

            

               

二、使用HttpURLConnection向服务器发送post请求

1、向服务器发送post请求

复制代码
    @Test
publicvoid addByUrl() throws Exception{
String encoding
="UTF-8";
String params
="[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
String path
="http://localhost:8083/xxxx/xxx/sim!add.do";
byte[] data = params.getBytes(encoding);
URL url
=new URL(path);
HttpURLConnection conn
= (HttpURLConnection)url.openConnection();
conn.setRequestMethod(
"POST");
conn.setDoOutput(
true);
//application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
conn.setRequestProperty(
"Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(
5*1000);
OutputStream outStream
= conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
//响应代码 200表示成功
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream();  
String result=new String(StreamTool.readInputStream(inStream), "UTF-8");

}

}
复制代码

                

2、从服务器读取数据   

//获取post请求过来的数据
byte[] data=StreamTool.readInputStream(request.getInputStream());
//[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]
String json=new String(data, "UTF-8");
posted on   Ruthless  阅读(53275)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
< 2011年9月 >
28 29 30 31 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 26 27 28 29 30 1
2 3 4 5 6 7 8

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