使用HttpURLConnection向服务器发送post和get请求
2015-12-23 13:00
501 查看
一、使用HttpURLConnection向服务器发送get请求
1、向服务器发送get请求
2、从服务器读取数据
二、使用HttpURLConnection向服务器发送post请求
1、向服务器发送post请求
2、从服务器读取数据
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");
相关文章推荐
- Android之Http通信——3.Android HTTP请求方式:HttpURLConnection
- TCP/IP模型是什么
- TCP三次握手的正确使用姿势
- 在Unity3D的网络游戏中实现资源动态加载
- Nginx Parsing HTTP Package、header/post/files/args Sourcecode Analysis
- 易语言注册码网络验证码自制
- TCP/IPillustrated 阅读笔记(一) introduction
- iOS网络收音机
- C#之网络
- 深入浅出HTTP协议(WEB开发和面试必备)
- iOS 网络访问安全问题解决方法App Transport Security policy requires the use of a secure connection
- 网络爬虫——爬取糗事百科笑料段子
- 关于Volley网络请求框架空指针异常问题
- Apache建设虚拟主机httpd-vh…
- [Network Analysis] 复杂网络分析总结
- 【转载】网络
- HTTP笔记(一)基本介绍
- Linux网络编程
- Linux服务器上监控网络带宽的18个常用命令
- 28家中国域名商保有量统计:有孚网络升至第十五