使用HttpURLConnection向服务器发送post和get请求
2016-01-18 11:05
691 查看
使用HttpURLConnection向服务器发送post和get请求
转自:/article/4621017.html一、使用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");
相关文章推荐
- android开源框架android-async-http使用
- 感谢“http://it.oyksoft.com/” 关于安装yum 于redhatEL4上的办法
- Xcode7 网络请求报错:The resource could not be loaded be
- Tinyhttpd轻量型Http Server
- 程序员的自我修养——计算机网络篇
- HTTP协议中PUT和POST使用区别
- iOS安全系列之一:HTTPS
- Android 网络框架学习之Retrofit,androidretrofit
- https双向认证(基于程序访问,j2ee和android上皆可用)
- linux下使用libmodbus库实现modbusTCP与modbusRTU功能
- 配置https双向认证过程实战(tomcat和浏览器交互)
- vmware下centos克隆功能对网络的设置
- vmware下centos克隆功能对网络的设置
- flex HTTPService浅析
- Android访问网络,使用HttpURLConnection还是HttpClient?
- 说说ToolBar以及仿QQ没网络提示的实现
- iOS 网络请求 时 出现 <null> 与 (null) 的 问题的处理方法
- 别说我懂社交网络: 关于社交网络分析的一头雾水
- 常用的网络驱动收包方式
- Sokcet方式请求HTTP/HTTPS的封装类HttpHelper